Leetcode31. Next Permutation

来源:互联网 发布:运动蓝牙耳机 知乎 编辑:程序博客网 时间:2024/05/29 17:23

31. 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

二、分析与思路

这道题目的意思很简单,就是要我们去寻找一个数组中比当前数组要大一级的数组排序(按字典序)。如果不存在,就按字典序对数组排序。这道题的思路是:
     1、从数组未往前找到一个相邻的数对,该数对满足后面的数要大于前面的数,为a,b。
     2、再次从数组末往前遍历,找到第一个数c,c满足c>a,进行交换。
     3、为了保证只是大一级的排序,我们再对b级b后面的数进行从小到大的排序。

三、代码

//快排public void sort(int[] nums, int low, int high) {int l = low;int h = high;int item = nums[l];while (l < h) {while (l < h && item < nums[h]) {h--;}if (l < h) {int temp = nums[h];nums[h] = nums[l];  nums[l] = temp;    l++;}while (l < h && item > nums[l]) {l++;}if (l < h) {int temp = nums[h];nums[h] = nums[l];  nums[l] = temp;    h--;}}if(l > low) {sort(nums, low, l-1);}if(h < high) {sort(nums, l + 1, high);}}public void nextPermutation(int[] nums) {int flag = 0;//从后往前遍历        for (int i = nums.length - 1; i >= 1; i--) {        //找到数据对a,b        if (nums[i] > nums[i - 1]) {        //寻找第一个比a大的数        for (int j = nums.length - 1; j >= i; j--) {        //交换排序        if (nums[j] > nums[i - 1]) {        int tmp = nums[j];        nums[j] = nums[i - 1];        nums[i - 1] = tmp;        flag = 1;        sort(nums, i, nums.length - 1);        break;        }        }        if (flag == 1) {        break;        }        }        }                //不存在,则排序        if (flag == 0) {        sort(nums, 0, nums.length - 1);        }    }


原创粉丝点击