題目:
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
思路:這道題還是有點難度的,參考了別人的思路,解法如下:以
以6,8,7,4,3,2
爲例:
- 首先從後往前遍歷,找到第一個不按遞增排列的元素,即
nums[i-1]
,上圖中的6。 - 再從後往前,找到第一個比
nums[i-1]
大的元素,即nums[j]
, 上圖中的7。 - 交換
nums[i-1]
和nums[j]
的位置,變成7, 8, 6, 4, 3, 2
。 - 對
i → nums.size()-1
的元素進行排序, 變成:7, 2, 3, 4, 6, 8
。
C++代碼如下:
void nextPermutation(vector<int>& nums) {
if (nums.size() <= 1)
return;
int right = nums.size() - 1;
int i = right,j = right,temp;
while (nums[i] <= nums[i - 1]) {
--i;
}
if (i == 0) {
sort(nums.begin(), nums.end());
return;
}
while (nums[i-1] >= nums[j])
{
--j;
}
temp = nums[j];
nums[j] = nums[i-1];
nums[i-1] = temp;
sort(nums.begin() + i,nums.end());
}