Skip to content

Commit 3651e5c

Browse files
committed
✨ search in rotated sorted array
1 parent 8d2c896 commit 3651e5c

File tree

1 file changed

+31
-0
lines changed
  • src/33-search-in-rotated-sorted-array

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/**
2+
* @param {number[]} nums
3+
* @return {void} Do not return anything, modify nums in-place instead.
4+
*/
5+
function nextPermutation(nums) {
6+
let i = nums.length - 2; // 向左遍历,i从倒数第二开始是为了nums[i+1]要存在
7+
while (i >= 0 && nums[i] >= nums[i + 1]) {
8+
// 寻找第一个小于右邻居的数
9+
i--;
10+
}
11+
12+
if (i >= 0) {
13+
// 这个数在数组中存在,从它身后挑一个数,和它换
14+
let j = nums.length - 1; // 从最后一项,向左遍历
15+
while (j >= 0 && nums[j] <= nums[i]) {
16+
// 寻找第一个大于 nums[i] 的数
17+
j--;
18+
}
19+
[nums[i], nums[j]] = [nums[j], nums[i]]; // 两数交换,实现变大
20+
}
21+
22+
// 如果 i = -1,说明是递减排列,如 3 2 1,没有下一排列,直接翻转为最小排列:1 2 3
23+
let l = i + 1;
24+
let r = nums.length - 1;
25+
while (l < r) {
26+
// i 右边的数进行翻转,使得变大的幅度小一些
27+
[nums[l], nums[r]] = [nums[r], nums[l]];
28+
l++;
29+
r--;
30+
}
31+
}

0 commit comments

Comments
 (0)