题目地址:
中文:https://leetcode-cn.com/problems/next-permutation/
英文:https://leetcode.com/problems/next-permutation/
题目描述:
Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
If such an arrangement is not possible, it must rearrange it as the lowest possible order (i.e., sorted in ascending order).
The replacement must be in place and use only constant extra memory.
Example 1:
Input: nums = [1,2,3]
Output: [1,3,2]
Example 2:
Input: nums = [3,2,1]
Output: [1,2,3]
Example 3:
Input: nums = [1,1,5]
Output: [1,5,1]
Example 4:
Input: nums = [1]
Output: [1]
Constraints:
1 <= nums.length <= 100
0 <= nums[i] <= 100
思路:
先想一下字典序什么样,比如123和321,最小的排列是单个数字从小到大,最大的排列是单个数字从大到小。所以如果判断最小,那就要看从左到右是不是非递减的;最大的话就是从右到左看是不是非递减的。
从右到左找到这样一个数对:右边的nums[i]大于左边的nums[i-1],然后重排包括这一对数在内右边的数字,找到一个比nums[i-1]大的就可以,剩下的数字按从小到大向右排列就可了。
题解:
class Solution {
public void nextPermutation(int[] nums) {
boolean flag_mid = false;
int m=0,n=0;
int last_ = nums.length-1;
while (last_>0){
for(int i=last_;i>0;--i){
if(nums[i-1]<nums[i]){
m = i-1;
n = i;
flag_mid = true;
break;
}
}
if(flag_mid) break;
--last_;
}//如果找到前面小于后面的情况
if(flag_mid){
//然后从i-1位开始重排列
int temp = nums[m];
int t=0;
Arrays.sort(nums,m,nums.length);
for(int i=m;i<nums.length;++i)
if(nums[i]>temp) {
t = i;
break;
}
temp = nums[m];
nums[m] = nums[t];
nums[t] = temp;
Arrays.sort(nums,m+1,nums.length);
}else
for(int i=0;i<nums.length/2;++i) {
int temp = nums[i];
nums[i] = nums[nums.length-i-1];
nums[nums.length-i-1] = temp;
}
}
}