Next Permutation

来源:互联网 发布:外星文明不存在 知乎 编辑:程序博客网 时间:2024/05/20 03:07

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

题目的意思:给定一个数组,重新排列这些数字,使得排列好的数字比原来的数字大,并且这个数字

是比原来数字大的集合中最小的。

思路:采用倒序查找的方法,查找到第一个递减的数字,然后在将这个递减数字后边的比它大

的最小的数字互换,然后将后边的数字升序排列。

public class Solution {    public void nextPermutation(int[] num) {        if(num.length <= 1)              return ;          for(int i = num.length - 2; i >= 0; i--)          {              if(num[i] < num[i+1])              {                  int j;                  for(j = num.length - 1; j >= i; j--)                      if(num[i] < num[j])                          break;                  // swap the two numbers.                  int tmp=num[i];                num[i]=num[j];                num[j]=tmp;                //sort the rest of arrays after the swap point.                  Arrays.sort(num, i+1, num.length);                  return ;              }          }          //reverse the arrays.          for(int i = 0; i < num.length / 2; i++)          {              int tmp = num[i];              num[i] = num[num.length - i - 1];              num[num.length - i - 1] = tmp;          }          return ;    }}

0 0
原创粉丝点击