您的位置:首页 > 其它

LeetCode 31. Next Permutation

2017-05-18 00:47 369 查看
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


Subscribe to see which companies asked this question.
题意是找到数组中元素顺序的下一个字典序,首先要考虑的是字典序是怎么形成的?靠前的元素先不动,逐步增大后面的元素,当后面的元素排列方法达到最大值时,才会去改变前一个元素。那么,我们只需要找到第一个非逆序的元素的位置即可(后面的元素已经全部逆序,这个非逆序的元素是下一步需要改变的),怎么改变?找到他后面元素中比他大的元素之中最小的那个和它交换(有点拗口),再把后面的元素sort一次即可。唯一的特殊情况是全部逆序(即达到字典序尽头,此时全部首尾互换元素即可)。
import java.util.Arrays;
public class Solution {
public void nextPermutation(int[] nums) {
if(nums.length<=1){
return;
}
int tem;
if(nums.length==2){
tem = nums[0];
nums[0] = nums[1];
nums[1] = tem;
return;
}
int i = nums.length-1;
for(;i>0;i--){
if(i!=0&&nums[i-1]<nums[i]){
break;
}
}
if(i==0){
Arrays.sort(nums);
return;
}
int min = nums[i];
int loc = i-1;
int index = i;
for(int z=nums.length-1;z>loc;z--){
if(nums[z]<=min&&nums[z]>nums[loc]){
min = nums[z];
index = z;
break;
}
}
tem = nums[loc];
nums[loc] = min;
nums[index] = tem;
int beg = loc+1;
int end = nums.length-1;
while(beg<end){
if(nums[beg]>nums[end]){
tem = nums[beg];
nums[beg] = nums[end];
nums[end] = tem;
}
beg++;
end--;
}
return;

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: