码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode OJ 31. Next Permutation

时间:2016-05-23 18:44:08      阅读:192      评论:0      收藏:0      [点我收藏+]

标签:

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

 

【题目分析】

题目要求我们对一个数组进行变换,变换后的结果是按照字典序比当前结果大的值中最小的那一个。如果我们不能找到下一个permutation(即当前顺序是这些数字最大的字典序排列),那么直接给出一个逆序的结果。

【思路】

1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1

分析这几个例子我们发现,如果一段序列是完全降序排列的,那么它的字典序是最大的,即对于这个序列中任意相邻的两个数a和b,a>=b。如果存在这样相邻的两个数a < b,那么通过变换我们可以找到它的下一个permutation。比如1,2,3 -> 1,3,2 我们交换2和3即可得到下一个结果。但是考虑这样一个序列: 4,6,5,我们看到4比6小,如果我们交换3和6得到的结果是6,4,5,这是我们想要的结果吗?并不是,我们发现,虽然相邻的4和6相邻且6比4大,但是在6的右边,还存在一个5它比4大,但是它比6小,如果我们交换5和4,得到的结果才是正确的。

因此这个过程可以这样来描述:

1. 找到第一个相邻的元组(a,b),满足a < b;

2. 如果这样的元组不存在,则将数组逆序,程序结束;

3. 如果这样的元组存在,我们找到从b开始数组以后的数中比a大的最小的那一个c。

4. 交换a和c,然后把c之后所有的数逆序,得到最后的结果,返回;

例如:[4,6,5,3,2,1]

第一步:找到元组(4,6) 4 < 6

第二步:找到6之后比4大的元素中最小的那个:5

第三步:交换4和5->[5,6,4,3,2,1,1]

第四步:把5之后的数字逆序->[5,1,1,2,3,4,6]

通过上述几个步骤,我们能正确地找出任意一个序列的next greater permutation

【java代码】

 1 public class Solution {
 2     public void nextPermutation(int[] nums) {
 3         int len = nums.length;
 4         if(len < 2) return;
 5         //找到第一个降序的数
 6         int index;
 7         for(index = len - 2; index >= 0; index--){
 8             if(nums[index] < nums[index+1]) break;
 9         }
10         //如果没有这样的数则直接返回逆序的结果
11         if(index < 0){
12             for(int i = 0,j = len - 1;i < j; i++, j--){
13                 int temp = nums[i];
14                 nums[i] = nums[j];
15                 nums[j] = temp;
16             }
17             return;
18         }
19         //找到降序的数的右边比它大的数中最小的那一个
20         int greater = index + 1;
21         while(greater < len - 1 && nums[greater + 1] > nums[index]){
22             greater ++;
23         }
24         //第一个降序的数和它右边比他大的最小的那个数交换
25         int temp = nums[index];
26         nums[index] = nums[greater];
27         nums[greater] = temp;
28         //第一个降序数位置之后所有数逆序,得到最后的结果
29         for(int i = index + 1, j = len - 1; i < j; i++, j--){
30             temp = nums[i];
31             nums[i] = nums[j];
32             nums[j] = temp;
33         }
34     }
35 }

 

LeetCode OJ 31. Next Permutation

标签:

原文地址:http://www.cnblogs.com/liujinhong/p/5520912.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!