-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathnextPermutation.cpp
More file actions
31 lines (30 loc) · 819 Bytes
/
Copy pathnextPermutation.cpp
File metadata and controls
31 lines (30 loc) · 819 Bytes
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
class Solution {
public:
void nextPermutation(vector<int>& nums) {
int n = nums.size();
int ind = -1;
for(int i = n-2; i>=0; i--) {
if(nums[i] < nums[i+1]) {
ind = i;
break;
}
}
if (ind == -1) {
reverse(nums.begin(), nums.end());
} else {
for (int i = n-1; i > ind; i--) {
if (nums[i] > nums[ind]) {
swap(nums[i], nums[ind]);
break;
}
}
int left = ind + 1;
int right = n - 1;
while (left < right) {
swap(nums[left], nums[right]);
left++;
right--;
}
}
}
};