-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathsolution1.js
58 lines (51 loc) · 976 Bytes
/
solution1.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/**
* https://leetcode.com/problems/pancake-sorting/
*
* 969. Pancake Sorting
*
* Medium
*
* 64ms 96.40%
* 36.7mb 37.63%
*/
const pancakeSort = A => {
const len = A.length
const ans = []
for (let i = len - 1; i >= 0; i--) {
const { index } = findMaxAndIndex(A, 0, i)
if (index === i) {
// 当前不需要翻转
continue
}
ans.push(index + 1)
A = reverseStartToEnd(A, index)
ans.push(i + 1)
A = reverseStartToEnd(A, i)
}
return ans
}
function reverseStartToEnd(array, end) {
const ans = []
for (let i = end; i >= 0; i--) {
ans.push(array[i])
}
for (let i = end + 1; i < array.length; i++) {
ans.push(array[i])
}
return ans
}
function findMaxAndIndex(arr, start, end) {
let max = Number.MIN_SAFE_INTEGER
let index = start
for (let i = start; i <= end; i++) {
const item = arr[i]
if (item > max) {
max = item
index = i
}
}
return {
max,
index
}
}