2017.9.25
可以理解为下一个排列的逆思路。
下一个排列,是将一个升序序列逐步调整为降序序列的过程。
上一个排列,可以理解为将一个降序序列逐步调整为升序序列的过程。
这样,首先就是从后向前遍历找到 num[flag]>num[flag+1]
然后再从后向前遍历,找到比num[flag]小的最大值。交换位置后,排序。注意这里的排序应该是降序的。
public class Solution {
/*
* @param nums: A list of integers
* @return: A list of integers that's previous permuation
*/
public List<Integer> previousPermuation(List<Integer> nums) {
// write your code here
int size = nums.size();
if(size <= 1){
return nums;
}
int flag = size-2;
Integer []num = new Integer[size];
num = nums.toArray(num);
// 从后向前遍历,找到num[flag] > num[flag + 1];记录flag的位置
while(flag >= 0){
if(num[flag] > num[flag+1]){
break;
}
flag--;
}
if(flag < 0){
Arrays.sort(num);
List<Integer> res = new LinkedList<>();
for(int i = num.length - 1;i>=0;i--){
res.add(num[i]);
}
return res;
}
// 从后向前遍历,找到比num[flag]小的最大的数。
int i = size - 1;
while(i>= 0){
if(num[i] < num[flag]){
int tmp = num[flag];
num[flag] = num[i];
num[i] = tmp;
break;
}
else{
i--;
}
}
Integer []arr_tmp = new Integer[size - flag];
arr_tmp = Arrays.copyOfRange(num, flag+1, size);
arr_tmp = turnList(arr_tmp);
for(int h = flag+1;h<size;h++){
num[h] = arr_tmp[h-flag-1];
}
return arrToList(num);
}
public List<Integer> arrToList(Integer []nums){
List<Integer> res = new LinkedList<Integer>();
int size = nums.length;
for(int i = 0; i < size; i++){
res.add(nums[i]);
}
return res;
}
public Integer[] turnList(Integer []nums){
int size = nums.length;
if(size <= 1){
return nums;
}
Arrays.sort(nums);
Integer []res = new Integer[size];
for(int i = 0; i< size; i++){
res[i] = nums[size-i-1];
}
return res;
}
}