下一个排列
解法一:遍历数组
import java.util.Arrays;
public class LeetCode_031 {
public static void nextPermutation(int[] nums) {
if (nums == null || nums.length < 2) {
return;
}
boolean handled = false;
int left = -1, right = -1;
for (int i = nums.length - 1; i > 0; i--) {
for (int j = i - 1; j >= 0; j--) {
if (nums[i] > nums[j]) {
if (j > left) {
left = j;
right = i;
} else if (j == left) {
if (i == right) {
left = j;
right = i;
}
}
handled = true;
break;
}
}
}
if (handled) {
exch(nums, left, right);
for (int x = right + 1; x < (nums.length + right + 1) / 2; x++) {
exch(nums, x, nums.length - 1 - (x - right) / 2);
}
for (int x = right - 1; x >= left + 1; x--) {
for (int y = x; y < nums.length - 1; y++) {
exch(nums, y, y + 1);
}
}
for (int x = left + 1; x < nums.length - 1; x++) {
if (nums[x] > nums[x + 1]) {
exch(nums, x, x + 1);
} else {
break;
}
}
} else {
for (int i = 0; i < nums.length / 2; i++) {
exch(nums, i, nums.length - 1 - i);
}
}
}
private static void exch(int[] nums, int left, int right) {
int temp = nums[right];
nums[right] = nums[left];
nums[left] = temp;
}
public static void main(String[] args) {
int[] nums = new int[]{4, 2, 0, 2, 3, 2, 0};
System.out.println("=====处理前=====");
Arrays.stream(nums).forEach(num -> {
System.out.print(num + " ");
});
System.out.println();
System.out.println("=====处理后=====");
nextPermutation(nums);
Arrays.stream(nums).forEach(num -> {
System.out.print(num + " ");
});
}
}