LeetCode 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

 


题目标签:Array
  这道题目给了我们一个array, 让我们in place 更改,改成 下一个更大的排列。 题目中给的例子都太短了。我们来挑一个长一点的例子。
  
  4,7,5,3,2  如何找到它的下一个更大的排列呢, 我们看4后面的, 7,5,3,2已经是最大的可能性了,所以只能把4换了,那只能找比4大一点的数字,5。那么结果就是
  5,7,4,3,2  这是把4和5交换之后的结果,但是这个不是4,7,5,3,2的下一个大的排列,我们需要得到的是5开头的最小的排列,所以要把5之后的array sort 一下,就变成
  5,2,3,4,7  这个就是答案。
 
  我们可以看出,第一步是从右边开始找,找到第一个数字,它不在从小到大的顺序里(这里从右向左看), 例子中就是 4。 如果没有找到这个数字的话,那么意味着 这个排列它是 (从左往右) 从大到小的排列。就像原题中给的例子3,2,1。 这样的话,只需要sort一下,让它恢复到最小的第一种可能性。
  接着,在找到了第一个数字4 的话,再一次从右边开始找,找到第一个比4大的数字,就是5,把这两个数字交换一下。
  最后,把5之后的array 给sort 一下,为什么要sort呢 -> 虽然我们把5换上来了,但是我们需要的仅仅是 下一个更大的排列,那么就需要把5开头的排序保持最小的值。
 
 

Java Solution:

Runtime beats 85.79% 

完成日期:07/13/2017

关键词:Array

关键点:找到需要被增大的那个数字A,再找到最接近于A且比A大的数字B,互换A和B,最后把B之后的所有数字sort

 1 public class Solution 
 2 {
 3     public void nextPermutation(int[] nums) 
 4     {
 5         // from right to left, find the first number which is not in ascending order
 6         for(int i=nums.length-1; i>=0; i--)
 7         {
 8             if(i == 0) // meaning all number are in ascending order
 9             {
10                 Arrays.sort(nums);
11                 return;
12             }
13             else if(nums[i] > nums[i-1])
14             {
15                 // from right to left, find the first number is greater than nums[index_num]
16                 for(int j=nums.length-1; j>=i-1; j--)
17                 {
18                     if(nums[j] > nums[i-1]) // swap them
19                     {
20                         int temp = nums[i-1];
21                         nums[i-1] = nums[j];
22                         nums[j] = temp;
23                         // sort the rest numbers after i - 1
24                         Arrays.sort(nums, i, nums.length);;
25                         return;
26                     }
27                 }
28             }
29         }
30     }
31     
32     
33 }

参考资料:

http://www.cnblogs.com/grandyang/p/4428207.html

LeetCode 算法题目列表 - LeetCode Algorithms Questions List

  
  
原文地址:https://www.cnblogs.com/jimmycheng/p/7169174.html