Skip to content

Commit 5e99d24

Browse files
committed
Add solution #969
1 parent 8f38205 commit 5e99d24

File tree

2 files changed

+53
-1
lines changed

2 files changed

+53
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# 1,053 LeetCode solutions in JavaScript
1+
# 1,054 LeetCode solutions in JavaScript
22

33
[https://leetcode.com/](https://leetcode.com/)
44

@@ -777,6 +777,7 @@
777777
966|[Vowel Spellchecker](./solutions/0966-vowel-spellchecker.js)|Medium|
778778
967|[Numbers With Same Consecutive Differences](./solutions/0967-numbers-with-same-consecutive-differences.js)|Medium|
779779
968|[Binary Tree Cameras](./solutions/0968-binary-tree-cameras.js)|Hard|
780+
969|[Pancake Sorting](./solutions/0969-pancake-sorting.js)|Medium|
780781
970|[Powerful Integers](./solutions/0970-powerful-integers.js)|Easy|
781782
976|[Largest Perimeter Triangle](./solutions/0976-largest-perimeter-triangle.js)|Easy|
782783
977|[Squares of a Sorted Array](./solutions/0977-squares-of-a-sorted-array.js)|Easy|

solutions/0969-pancake-sorting.js

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
/**
2+
* 969. Pancake Sorting
3+
* https://leetcode.com/problems/pancake-sorting/
4+
* Difficulty: Medium
5+
*
6+
* Given an array of integers arr, sort the array by performing a series of pancake flips.
7+
*
8+
* In one pancake flip we do the following steps:
9+
* - Choose an integer k where 1 <= k <= arr.length.
10+
* - Reverse the sub-array arr[0...k-1] (0-indexed).
11+
*
12+
* For example, if arr = [3,2,1,4] and we performed a pancake flip choosing k = 3, we reverse
13+
* the sub-array [3,2,1], so arr = [1,2,3,4] after the pancake flip at k = 3.
14+
*
15+
* Return an array of the k-values corresponding to a sequence of pancake flips that sort arr.
16+
* Any valid answer that sorts the array within 10 * arr.length flips will be judged as correct.
17+
*/
18+
19+
/**
20+
* @param {number[]} arr
21+
* @return {number[]}
22+
*/
23+
var pancakeSort = function(arr) {
24+
const result = [];
25+
let end = arr.length;
26+
27+
while (end > 1) {
28+
const maxIndex = arr.indexOf(end);
29+
30+
if (maxIndex !== end - 1) {
31+
if (maxIndex !== 0) {
32+
result.push(maxIndex + 1);
33+
reverse(arr, maxIndex);
34+
}
35+
result.push(end);
36+
reverse(arr, end - 1);
37+
}
38+
end--;
39+
}
40+
41+
return result;
42+
};
43+
44+
function reverse(arr, k) {
45+
let left = 0;
46+
while (left < k) {
47+
[arr[left], arr[k]] = [arr[k], arr[left]];
48+
left++;
49+
k--;
50+
}
51+
}

0 commit comments

Comments
 (0)