Leetcode31 Next Permutation

来源:互联网 发布:caeses软件 编辑:程序博客网 时间:2024/05/16 15:26

Next Permutation

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

Solution

  • 可以举例观察特点。
    • 345
    • 354
    • 435
    • 453
    • 534
    • 543
    • 345
  • 如上所述,实际操作过程可以分为三步:
    • 第一步,从后往前找,找到第一个降序,比如453,45这里是一个降序,降序处的数为4;
    • 第二步,从后往前找找到第一个比4大的那个数,这里是5,交换4和5的位置;
    • 第三步,将原先4位置后面的数进行翻转,比如这里是先得到543,然后再将43翻转得到最终的答案为534。
  • 用代码表示如下:
public class Solution {    public void nextPermutation(int[] nums) {        int n = nums.length;        int i = n-2, j = n-1, temp;        for(;i>=0;i--) if(nums[i]<nums[i+1]) break;//从后往前找到第一个降序        if(i>=0){            temp = nums[i];            for(;j>=0;j--) if(nums[j]>temp) break;//从后往前找到第一个比降序处的数大的数            nums[i] = nums[j];//交换这两个数            nums[j] = temp;        }        for(i++,j=n-1;i<j;i++,j--){//翻转后面的所有数            temp = nums[j];            nums[j] = nums[i];            nums[i] = temp;        }            }}
  • 当然,有些解法里面在第二步的时候用二分法去找比4大的那个数,这样运行速度稍微会好些,但是时间复杂度仍为O(N),并且代码也要更加复杂一些。感兴趣的可以自己尝试去实现一下。
0 0
原创粉丝点击