题目
题目链接
题解
class Solution {
public void nextPermutation(int[] nums) {
if (nums == null) {
return;
}
int n = nums.length;
if (n == 1 || n == 0) {
return;
}
for (int i = n - 2; i >= 0; i--) {
if (nums[i] < nums[i + 1]) {
for (int j = n - 1; j > i; j--) {
if (nums[i] < nums[j]) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
break;
}
}
reverse(nums, i + 1, n - 1);
break;
} else if (i == 0) {
reverse(nums, 0, n - 1);
}
}
}
private void reverse(int[] nums, int from, int to) {
if (nums == null || nums.length <= 1 || from < 0 || from >= to || from > nums.length - 1 || to < 0 || to > nums.length - 1) {
return;
}
for (int i = from, j = to; i < j; i++, j--) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}
}