import java.util.Arrays;
//Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
//If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).
//The replacement must be in-place, do not allocate extra memory.
//Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
//1,2,3 → 1,3,2
//3,2,1 → 1,2,3
//1,1,5 → 1,5,1
//题意:输出全排列的下一个组合
//1.换 2.找最接近的 3.换 4.升序
public class Solution {
public static void main(String[] args) {
int[] input = {5,1,1};
nextPermutation(input);
for(int i = 0;i<input.length;i++){
System.out.println(input[i]);
}
}
public static void nextPermutation(int[] nums) {
if(nums.length == 1){ //若输入数组中只有一个数,则直接返回
return;
}
int i = nums.length-2;
while(i>=0){ //找到要交换的第一个字符下标
if(nums[i]<nums[i+1]) break;
i--;
}
if(i == -1){ //若字符串是降序排列的,则输出全排列的第一种组合
Arrays.sort(nums);
return;
}
int change1 = i; //change1,change2分别是交换的两个值的下标
int change2 = 0;
for(;i<nums.length;i++){ //找到比要交换第一个值大,且最接近的值,就是要交换的第二个值
int temp = nums[i]-nums[change1];
int cha = 100;
if(temp<cha&&temp>0){
cha = temp;
change2 = i;
}
}
int temp = nums[change1]; //交换这两个值
nums[change1] = nums[change2];
nums[change2] = temp;
for(int j = change1+1;j<nums.length-1;j++){ //交换之后第一个值下标之后的字符升序排序
for(int k = j+1;k<nums.length;k++){
if(nums[j]>nums[k]){
int temp1 = nums[k];
nums[k] = nums[j];
nums[j] = temp1;
}
}
}
}
}
leetcode 31. Next Permutation
最新推荐文章于 2024-09-20 15:32:13 发布