-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNext Permutation.cpp
More file actions
53 lines (45 loc) · 1.12 KB
/
Copy pathNext Permutation.cpp
File metadata and controls
53 lines (45 loc) · 1.12 KB
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
//Problem Statement Link - https://leetcode.com/problems/next-permutation/
// Singe Pass Approach
// Time : O(n); Space : 0(1)
class Solution {
public:
void nextPermutation(vector<int>& nums) {
int i = nums.size() - 1;
while (i >= 0 && nums[i + 1] <= nums[i]) {
i--;
}
if (i >= 0) {
int j = nums.size() - 1;
while (j >= 0 && nums[j] <= nums[i]) {
j--;
}
swap(nums, i, j);
}
reverse(nums, i + 1);
}
private:
void swap(vector<int>& nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
void reverse(vector<int>& nums, int start) {
int i = start, j = nums.size()- 1;
while (i < j) {
swap(nums, i, j);
i++;
j--;
}
}
};
// Using Library Function
class Solution {
public:
void nextPermutation(vector<int>& nums) {
bool val=next_permutation(nums.begin(),nums.end());
if(val==false)
{
sort(nums.begin(),nums.end());
}
}
};