Repository navigation
Expand file tree
/
Copy path31.next-permutation.java
More file actions
66 lines (62 loc) · 1.76 KB
/
Copy path31.next-permutation.java
File metadata and controls
66 lines (62 loc) · 1.76 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
54
55
56
57
58
59
60
61
62
63
64
65
/*
* @lc app=leetcode id=31 lang=java
*
* [31] Next Permutation
*/
// @lc code=start
class Solution {
public void nextPermutation(int[] nums) {
/*
* 1. finding the last peak element
* 2. find nearest lower element on the left
* 3. swap it with next greater element on the right
* 4. sorting with ascending order after the nearest lower element
* Special case:
* descending order => ascending order
*/
boolean descendingFlag = true;
int arrlen = nums.length;
int peak = arrlen-1;
int newPeak =0;
if(arrlen == 1) return;
// check descending case
for(int i = arrlen-1;i > 0;i--){
if(nums[i-1]<nums[i]) {
peak = i;
descendingFlag = false;
break;
}
}
if(descendingFlag){
// reverse the array
int temp,j;
for(int i = 0; i <= (arrlen-1)/2;i++){
j = arrlen-1 - i;
temp = nums[j];
nums[j]=nums[i];
nums[i]= temp;
}
return;
}
int temp = 0;
// find the nearest lower element's index
for(int i = peak-1; i >= 0; i--){
if(nums[i]<nums[peak]){
newPeak = i;
break;
}
}
// Swap the new peak with the next greater element
int nextgreater = arrlen-1;
while (nums[nextgreater] <= nums[newPeak]) {
nextgreater--;
}
temp = nums[newPeak];
nums[newPeak] = nums[nextgreater];
nums[nextgreater] = temp;
// sorting
java.util.Arrays.sort(nums, newPeak + 1, arrlen);
return;
}
}
// @lc code=end