您的位置:首页 > 其它

【LeetCode】31.Next Permutation(Medium)解题报告

2018-01-03 20:17 513 查看
【LeetCode】31.Next Permutation(Medium)解题报告

题目地址:https://leetcode.com/problems/next-permutation/description/

题目描述:

  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

  可能有重复数字,输出全部排列。推荐解法一。面试常出现

Solution1:

//时间复杂度O(n)
//空间复杂度O(1)
/*
1 2 7 4 3 1
^
1 2 7 4 3 1
^
1 3 7 4 2 1

1 3 1 2 4 7

*/

class Solution {
public void nextPermutation(int[] nums) {
if(nums==null || nums.length==0) return;
int firstSmall = -1;
for(int i=nums.length-2 ; i>=0 ; i--){
if(nums[i]<nums[i+1]){
firstSmall = i;
break;
}
}
if(firstSmall==-1){
reverse(nums,0,nums.length-1);
return;
}
int firstLarge = -1;
for(int i=nums.length-1 ; i>=0 ; i--){
if(nums[i]>nums[firstSmall]){
firstLarge = i;
break;
}
}
swap(nums,firstSmall,firstLarge);
reverse(nums,firstSmall+1,nums.length-1);
}
public void swap(int[] nums,int i,int j){
int temp = nums[i];
nums[i++] = nums[j];
nums[j--] = temp;
}
public void reverse(int[] nums,int i,int j){
while(i<j){
swap(nums,i++,j--);
}
}

}


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