-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNextPermutation.h
56 lines (50 loc) · 1.47 KB
/
NextPermutation.h
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
49
50
51
52
53
54
55
56
//
// NextPermutation.h
//
//
// https://leetcode.com/problems/next-permutation/description/
//
#ifndef NextPermutation_h
#define NextPermutation_h
class Solution {
public:
void nextPermutation(vector<int>& nums) {
if (nums.size() < 2)
{
return;
}
int endingIndex = 0;
while (true)
{
bool found = false;
for (int i = nums.size() - 1; i >= endingIndex + 1; i--)
{
if (nums[i] > nums[i - 1])
{
int target = nums[i - 1];
int targetIndex = 0;
int minDiff = INT_MAX;
int minValue = 0;
for (int j = i; j < nums.size(); j++)
{
if (nums[j] - target > 0 && nums[j] - target < minDiff)
{
minDiff = nums[j] - target;
targetIndex = j;
minValue = nums[j];
}
}
int temp = target;
nums[i - 1] = minValue;
nums[targetIndex] = target;
endingIndex = i;
found = true;
break;
}
}
sort(nums.begin() + endingIndex, nums.end());
break;
}
}
};
#endif /* NextPermutation_h */