Last active
December 13, 2015 22:08
-
-
Save zhoutuo/4981816 to your computer and use it in GitHub Desktop.
Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers. If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order). The replacement must be in-place, do not allocate extra memory. Here are some examples. Inputs are in the left…
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
void nextPermutation(vector<int> &num) { | |
// Start typing your C/C++ solution below | |
// DO NOT write int main() function | |
bool found = false; | |
int left = -1; | |
int right = num.size(); | |
for(int i = num.size() - 1; i >= 0; --i) { | |
int cur = num[i]; | |
for(int j = i - 1; j >= 0; --j) { | |
if(num[j] < num[i] && j >= left) { | |
found = true; | |
if(left == j) { | |
right = num[right] > num[i] ? i : right; | |
} else { | |
right = i; | |
} | |
left = j; | |
break; | |
} | |
} | |
} | |
if(!found) { | |
sort(num.begin(), num.end()); | |
return; | |
} | |
swap(num[left], num[right]); | |
sort(num.begin() + left + 1, num.end()); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment