MrainW's Home

All things come to those who wait!

0%

LeetCode 31. Next Permutation

Question

Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.

If such an arrangement is not possible, it must rearrange it as the lowest possible order (i.e., sorted in ascending order).

The replacement must be in place and use only constant extra memory.

https://leetcode.com/problems/next-permutation/

  • Solution1
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
class Solution {
public void nextPermutation(int[] nums) {
if (nums == null || nums.length == 0) return;
int replace = nums.length - 2;
//后面的数确定是倒序排列的
while (replace >= 0) {
if (nums[replace] < nums[replace + 1]) break;
replace--;
}
if (replace < 0) {
Arrays.sort(nums);
return;
}
int lgrIdx = replace + 1;
//while 找到的是最接近的比replace位大的数的下一位
while (lgrIdx < nums.length && nums[lgrIdx] > nums[replace]) {
lgrIdx++;
}
int tmp = nums[replace];
nums[replace] = nums[lgrIdx - 1];
nums[lgrIdx - 1] = tmp;
//nums.length不参加排序
Arrays.sort(nums, replace + 1, nums.length);
}
}

Complexity:

Time complexity: O(nlogn)

Space complexity: O(1)

Welcome to my other publishing channels