forked from Sunchit/Coding-Decoded
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNextPermutation.java
47 lines (36 loc) · 953 Bytes
/
NextPermutation.java
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
class Solution {
// TC : O(N)
// SC: O(1)
public void nextPermutation(int[] nums) {
int first = nums.length-1;
while(first>=1 && nums[first-1] >=nums[first]){
first--;
}
if(first==0){
Arrays.sort(nums);
return;
}
first--;
int second = nums.length-1;
while(first<second && nums[first] >=nums[second]){
second--;
}
swap(nums, first, second);
int start = first+1;
int end = nums.length -1;
while(start < end){
int temp = nums[start];
nums[start] = nums[end] ;
nums[end] = temp;
end--;
start++;
}
}
private void swap(int[] nums, int first, int second){
if(first!=second){
int temp = nums[second];
nums[second] = nums[first];
nums[first] = temp;
}
}
}