-
Notifications
You must be signed in to change notification settings - Fork 0
/
Next_Permutation.java
82 lines (71 loc) · 1.8 KB
/
Next_Permutation.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
https://leetcode.com/problems/next-permutation
//monu bhiya solution
class Solution {
public void nextPermutation(int[] nums) {
for(int i = nums.length-2;i>=0;i--){
if(nums[i]<nums[i+1]){
p=i;
break;
}
}
int q = 0;
for(int i = nums.length-1;i>p;i--){
if(nums[i]>nums[p]){
q=i;
break;
}
}
if(p == 0 && q == 0){
Range_reverse(nums,0,arr.length-1);
return;
}
int temp = nums[p];
nums[p] = nums[q];
nums[q] = temp;
Range_reverse(nums,p+1,nums.length-1);
public static void Range_reverse(int[] arr, int i, int j) {
while (i < j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
j--;
}
}
}
class Solution {
public void nextPermutation(int[] nums) {
int mark = -1;
//find first decreasing digit
for(int i = nums.length-1;i>0;i--){
if(nums[i] > nums[i-1]){
mark = i-1;
break;
}
}
if(mark == -1){
reverse(nums,0,nums.length-1);
return;
}
int idx = nums.length-1;
for(int i = nums.length-1;i>=mark+1;i--){
if(nums[i]>nums[mark]){
idx = i;
break;
}
}
swap(nums,mark,idx);
reverse(nums,mark+1,nums.length-1);
}
private void swap(int[]nums,int i, int j){
int t = nums[i];
nums[i] = nums[j];
nums[j] = t;
}
private void reverse(int []nums,int i , int j){
while(i<j){
swap(nums,i,j);
i++;j--;
}
}
}