-
Notifications
You must be signed in to change notification settings - Fork 0
/
NextPermutation.cpp
40 lines (39 loc) · 972 Bytes
/
NextPermutation.cpp
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
class NextPermutation {
public:
void nextPermutation(vector<int>& nums) {
if (nums.size() == 0) {
return;
}
int i = nums.size() - 2;
while (i >= 0 && nums[i] >= nums[i + 1]) {
i--;
}
if (i >= 0) {
int j = nums.size() - 1;
while (nums[j] <= nums[i]) {
j--;
}
swap(nums[i], nums[j]);
}
reverse(nums, i + 1, nums.size() - 1);
}
private:
void reverse(vector<int>& nums, int left, int right) {
while (left < right) {
swap(nums[left++], nums[right--]);
}
}
// we can also use binary search to find the index j
int search(vector<int>& nums, int left, int right, int target) {
while (left < right - 1) {
int mid = left + (right - left) / 2;
if (nums[mid] <= target) {
right = mid - 1;
} else {
left = mid;
}
}
// garuanteed to exist the smallest larger than the target
return nums[right] > target ? right : left;
}
};