Skip to content

Commit a3c6cd4

Browse files
author
applewjg
committed
update
Change-Id: Ib4f4298d96e771e925dbcd4c5a9f960b9ef575f5
1 parent 0be8e9b commit a3c6cd4

File tree

1 file changed

+8
-11
lines changed

1 file changed

+8
-11
lines changed

NextPermutation.h

Lines changed: 8 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
/*
2-
Author: Annie Kim, [email protected]
2+
Author: Annie Kim, [email protected] : King, [email protected]
33
Date: May 6, 2013
4+
Update: Dec 16, 2014
45
Problem: Next Permutation
56
Difficulty: Medium
67
Source: http://leetcode.com/onlinejudge#question_31
@@ -26,15 +27,11 @@
2627
class Solution {
2728
public:
2829
void nextPermutation(vector<int> &num) {
29-
int i = num.size() - 1;
30-
while (i > 0 && num[i] <= num[i-1])
31-
i--;
32-
sort(num.begin() + i, num.end());
33-
if (i == 0)
34-
return;
35-
int j = i;
36-
while (j < num.size() && num[j] <= num[i-1])
37-
j++;
38-
swap(num[j], num[i-1]);
30+
int n = num.size(), i = n - 1, j = 0;
31+
while(i > 0 && num[i-1] >= num[i]) --i;
32+
reverse(num.begin() + i,num.end());
33+
if (i == 0) return;
34+
while (i+j < n && num[i-1] >= num[i+j]) ++j;
35+
swap(num[i-1], num[i+j]);
3936
}
4037
};

0 commit comments

Comments
 (0)