【Leetcode】Next Permutation
來源:程序員人生 發布時間:2016-06-25 15:29:49 閱讀次數:2440次
題目鏈接:https://leetcode.com/problems/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, do not allocate 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
思路:
見注釋。。。。
算法:
public void nextPermutation(int[] nums) {
int pos = ⑴;
// 找到最后1個升序位置
for (int i = nums.length - 1; i >= 1; i--) {
if (nums[i] > nums[i - 1]) {
pos = i - 1;
break;
}
}
// 如果沒有升序 如3 2 1 需要反轉為1 2 3
if (pos < 0) {
nums = reverse(nums, 0, nums.length - 1);
return;
}
// 存在升序 找到pos以后最后1個大于pos的位置
// 舉例 如1 2 5 4 3 1下1個排列應當是 1 3 1 2 4 5,
// 首先定位pos元素為2;找到元素3;二者交換:1 3 5 4 2 1;將5~1反轉;
for (int i = nums.length - 1; i > pos; i--) {
if (nums[i] > nums[pos]) {
int tmp = nums[i];
nums[i] = nums[pos];
nums[pos] = tmp;
break;
}
}
// 將pos以后元素全部反轉
nums = reverse(nums, pos + 1, nums.length - 1);
}
public int[] reverse(int nums[], int start, int end) {
while (start < end) {
int tmp = nums[start];
nums[start] = nums[end];
nums[end] = tmp;
start++;
end--;
}
return nums;
}
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈