-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.java
More file actions
41 lines (37 loc) · 1.03 KB
/
Solution.java
File metadata and controls
41 lines (37 loc) · 1.03 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
package leetcode._31_;
import java.util.Arrays;
class Solution {
public void nextPermutation(int[] nums) {
this.isDone(nums, 0);
}
private boolean isDone(int[] nums, int begin) {
int end = nums.length;
if (end - begin < 1) {
return true;
}
if (end - begin == 2) {
boolean result = nums[end - 1] > nums[begin];
swap(nums, begin, end);
return result;
}
if (this.isDone(nums, begin + 1)) {
return true;
} else {
int tmp = begin + 1;
while (tmp < end) {
if (nums[begin] < nums[tmp]) {
swap(nums,begin,tmp);
return true;
}
tmp++;
}
Arrays.sort(nums, begin, end);
return false; // [1,3,5,2,4]
}
}
private void swap(int[] nums, int begin, int end) {
int temp = nums[end - 1];
nums[end - 1] = nums[begin];
nums[begin] = temp;
}
}