Skip to content

Commit eb3f1f0

Browse files
authored
Added C++ Solution (#112)
* Added C++ solution 31. Next Permutation C++ solution * Update README.md * Update _31.cpp
1 parent 4069c14 commit eb3f1f0

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-1
lines changed

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -990,7 +990,7 @@ _If you like this project, please leave me a star._ ★
990990
|34|[Search for a Range](https://leetcode.com/problems/search-for-a-range/)|[Solution](../master/src/main/java/com/fishercoder/solutions/_34.java)||Medium|Array, Binary Search
991991
|33|[Search in Rotated Sorted Array](https://leetcode.com/problems/search-in-rotated-sorted-array/)|[Solution](../master/src/main/java/com/fishercoder/solutions/_33.java)||Medium|Binary Search
992992
|32|[Longest Valid Parentheses](https://leetcode.com/problems/longest-valid-parentheses/)|[Solution](../master/src/main/java/com/fishercoder/solutions/_32.java)||Hard|Stack, DP
993-
|31|[Next Permutation](https://leetcode.com/problems/parents-permutation)|[Solution](../master/src/main/java/com/fishercoder/solutions/_31.java)||Medium|Array
993+
|31|[Next Permutation](https://leetcode.com/problems/parents-permutation)|[Solution](../master/src/main/java/com/fishercoder/solutions/_31.java), [C++](../master/cpp/_31.cpp)||Medium|Array
994994
|30|[Substring with Concatenation of All Words](https://leetcode.com/problems/substring-with-concatenation-of-all-words/)|[Solution](../master/src/main/java/com/fishercoder/solutions/_30.java)||Hard| HashMap
995995
|29|[Divide Two Integers](https://leetcode.com/problems/divide-two-integers/)|[Solution](../master/src/main/java/com/fishercoder/solutions/_29.java)||Medium|
996996
|28|[Implement strStr()](https://leetcode.com/problems/implement-strstr/)|[Solution](../master/src/main/java/com/fishercoder/solutions/_28.java)||Easy| String

cpp/_31.cpp

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
class Solution {
2+
public:
3+
void nextPermutation(vector<int>& nums) {
4+
5+
int i1;
6+
int i2;
7+
bool hasPermutation = false;
8+
9+
for(int i=nums.size()-1; i>0; i--){
10+
if(nums[i-1]<nums[i]){
11+
i1 = i-1;
12+
i2 = i;
13+
hasPermutation = true;
14+
break;
15+
}
16+
}
17+
18+
if(hasPermutation){
19+
int j=i2;
20+
for(int i=nums.size()-1; i>i1; i--){
21+
if(nums[i]>nums[i1]){
22+
j=i;
23+
break;
24+
}
25+
}
26+
swap(nums[i1], nums[j]);
27+
reverse(nums.begin()+i1+1, nums.end());
28+
}else{
29+
sort(nums.begin(), nums.end());
30+
}
31+
32+
}
33+
};

0 commit comments

Comments
 (0)