Skip to content

Commit 8fb4b9a

Browse files
committed
fd
1 parent df52936 commit 8fb4b9a

File tree

3 files changed

+17
-29
lines changed

3 files changed

+17
-29
lines changed

solution/src/main/java/com/inuker/solution/MoveZeroes.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ private void swap(int[] nums, int i, int j) {
2929
/**
3030
* 如果不要求保持顺序,且写的次数最少
3131
*/
32-
public int moveZeroes2(int[] nums) {
32+
public void moveZeroes2(int[] nums) {
3333
for (int i = 0, j = nums.length - 1; j > i; ) {
3434
if (nums[i] != 0) {
3535
i++;

solution/src/main/java/com/inuker/solution/NextPermutation.java

Lines changed: 9 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,10 @@
99
*/
1010
public class NextPermutation {
1111

12+
/**
13+
* 思路是从右往左找到升序转降序的转折点nums[i]
14+
* 然后从升序中找到一个大于nums[i-1]的最小数与i-1交换,然后对升序整体revert为降序即可
15+
*/
1216
public void nextPermutation(int[] nums) {
1317
int i = nums.length - 1;
1418

@@ -23,34 +27,13 @@ public void nextPermutation(int[] nums) {
2327
return;
2428
}
2529

26-
int index = searchSwapPoint(nums, i, nums.length - 1, nums[i - 1]);
27-
28-
swap(nums, i - 1, index);
29-
revert(nums, i, nums.length - 1);
30-
}
31-
32-
private int searchSwapPoint(int[] nums, int left, int right, int target) {
33-
while (left <= right) {
34-
int mid = left + ((right - left) >> 1);
35-
36-
if (left == mid) {
37-
if (target >= nums[right]) {
38-
return right - 1;
39-
} else {
40-
return right;
41-
}
42-
}
43-
44-
if (target > nums[mid]) {
45-
right = mid - 1;
46-
} else if (target < nums[mid]) {
47-
left = mid;
48-
} else {
49-
right = mid - 1;
30+
for (int j = nums.length - 1; j >= i; j--) {
31+
if (nums[j] > nums[i - 1]) {
32+
swap(nums, j, i - 1);
33+
revert(nums, i, nums.length - 1);
34+
break;
5035
}
5136
}
52-
53-
throw new IllegalStateException("");
5437
}
5538

5639
private void swap(int[] nums, int left, int right) {

test/src/main/java/com/inuker/test/main.java

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
package com.inuker.test;
22

3+
import com.inuker.solution.NextPermutation;
34
import com.inuker.solution.SearchForARange;
45
import com.leetcode.library.ListNode;
56
import com.leetcode.library.RandomListNode;
@@ -28,9 +29,13 @@
2829
public class main {
2930

3031
public static void main(String[] args) {
31-
int[] arr = new int[] {
32-
0, 0, 3, 4, 5, 0, 0
32+
int[] arr = new int[]{
33+
2, 2, 0, 4, 3, 1
3334
};
35+
new NextPermutation().nextPermutation(arr);
36+
for (int n : arr) {
37+
System.out.print(n + " ");
38+
}
3439
}
3540

3641
}

0 commit comments

Comments
 (0)