forked from seanprashad/leetcode-patterns
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path31_Next_Permutation.java
44 lines (37 loc) · 970 Bytes
/
31_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
classSolution {
publicvoidnextPermutation(int[] nums) {
if (nums == null || nums.length == 0) {
return;
}
intn = nums.length - 1, idx = -1;
for (inti = n - 1; i >= 0; i--) {
if (nums[i] < nums[i + 1]) {
idx = i;
break;
}
}
if (idx == -1) {
reverseArray(nums, 0, n);
return;
}
for (inti = n; i >= 0; i--) {
if (nums[i] > nums[idx]) {
swap(nums, i, idx);
break;
}
}
reverseArray(nums, idx + 1, n);
}
privatevoidreverseArray(int[] nums, intstart, intend) {
while (start < end) {
swap(nums, start, end);
++start;
--end;
}
}
privatevoidswap(int[] nums, inti, intj) {
inttemp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}