-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnextPermutation.cpp
More file actions
48 lines (45 loc) · 1.33 KB
/
nextPermutation.cpp
File metadata and controls
48 lines (45 loc) · 1.33 KB
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <vector>
#include <algorithm>
using namespace std;
class Solution
{
public:
void nextPermutation(vector<int> &nums)
{
//使用双指针来进行遍历数组
int left = nums.size() - 2;
int right = left + 1;
bool ShouldBreak = false;
//开始遍历,找到直到nums[i] < nums[i + 1]就停
for(left;left >= 0;left--,right--)
{
if(nums[left] < nums[right])
{
//此时left记录的就是那个正好比右边那个数小的下标
//再次遍历,直到nums[j] > nums[left]
for(int j = nums.size() - 1;j >= 0;j--)
{
if(nums[j] > nums[left])
{
//交换这两个位置上的数
int temp = nums[j];
nums[j] = nums[left];
nums[left] = temp;
ShouldBreak = true;
// 最终反转
reverse(nums.begin() + left + 1,nums.end());
break;
}
}
}
if (ShouldBreak)
{
break;
}
}
if(!ShouldBreak)
{
sort(nums.begin(),nums.end());
}
}
};