[leetcode]31. Next Permutation下一个排列

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

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

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

Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.

1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1

思路:

给定一个排列,按照字典序把下一个排列找出来。

Solution1:

[leetcode]31. Next Permutation下一个排列

[leetcode]31. Next Permutation下一个排列

[leetcode]31. Next Permutation下一个排列

[leetcode]31. Next Permutation下一个排列

[leetcode]31. Next Permutation下一个排列

[leetcode]31. Next Permutation下一个排列

[leetcode]31. Next Permutation下一个排列

code:

 /*
Time: O(n). We travese the given array
Space: O(1). We only used constant extra space.
*/ class Solution {
public void nextPermutation(int[] nums) {
// corner case
if (nums == null || nums.length == 0) return; int replace = nums.length - 2; //为何初始化为这个?因为下面要replace 和replace +1 比较
while (replace >= 0) {
if (nums[replace] < nums[replace + 1]) break;//从右往左扫
replace--;
}
if (replace < 0) {//说明数组总没有出现nums[replace]<nums[replace+1], 则数组为 654321 这种排序
Arrays.sort(nums); //返回题干说述的升序排列
return;
}
int lgrIdx = replace + 1;
//从nums[replace]往后,开始找剩下数字中,大于且最接近的nums[replace]的值
while (lgrIdx < nums.length && nums[lgrIdx] > nums[replace]) {
lgrIdx++;
}
int temp = nums[replace];
nums[replace] = nums[lgrIdx - 1];
nums[lgrIdx - 1] = temp;
Arrays.sort(nums, replace + 1, nums.length);
}
}
上一篇:【LeetCode每天一题】Next Permutation(下一个排列)


下一篇:lintcode:next permutation下一个排列