-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNext Permutation.java
More file actions
35 lines (30 loc) · 820 Bytes
/
Next Permutation.java
File metadata and controls
35 lines (30 loc) · 820 Bytes
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
class Solution {
public void nextPermutation(int[] nums) {
int i = nums.length - 2;
while( i >= 0 && nums[i] >= nums[i+1]){
i--;
}
if( i == -1){
reverse( nums, 0, nums.length -1 );
return;
}
int j = nums.length-1;
while( nums[i] >= nums[j]){
j--;
}
swap( nums, i, j);
reverse(nums, i+1, nums.length -1);
}
private void swap(int nums[] , int i , int j){
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
private void reverse(int nums[] , int start , int end){
while( start < end){
swap(nums, start , end);
start++;
end--;
}
}
}