Skip to content

Commit 6082844

Browse files
committed
3
1 parent 53b34c6 commit 6082844

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

NextPermutation/NextPermutation.cpp

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
class Solution {
2+
public:
3+
void nextPermutation(vector<int>& num) {
4+
// Start typing your C/C++ solution below
5+
// DO NOT write int main() function
6+
7+
int n = num.size();
8+
if (n <= 1) return;
9+
10+
bool found = false;
11+
int i, p, maxval = INT_MIN;
12+
for (i = n - 1; i >= 1; i--) {
13+
if (maxval < num[i]) {
14+
maxval = num[i];
15+
}
16+
if (num[i-1] < maxval) {
17+
int delta = INT_MAX;
18+
for (int j = i; j < n; j++) {
19+
if (num[j] > num[i-1] && num[j] - num[i-1] < delta)
20+
p = j;
21+
}
22+
found = true;
23+
break;
24+
}
25+
}
26+
if (!found) {
27+
reverse(num.begin(), num.end());
28+
}
29+
else {
30+
swap(num[p], num[i-1]);
31+
sort(num.begin() + i, num.end());
32+
}
33+
}
34+
};

0 commit comments

Comments
 (0)