LeetCode: Next Permutation 解题报告

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 1:

1.  From the tail to find the first digital which drop
  example: 12 4321

首先我们找到从尾部到头部第一个下降的digit. 在例子中是:2

2. 把从右到左第一个比dropindex大的元素换过来。

3. 把dropindex右边的的序列反序

4. 如果1步找不到这个index ,则不需要执行第二步。

 1 public class Solution {
 2     public void nextPermutation(int[] num) {
 3         if (num == null) {
 4             return;
 5         }
 6         
 7         int len = num.length;
 8         
 9         // Find the index which drop.
10         int dropIndex = -1;
11         for (int i = len - 1; i >= 0; i--) {
12             if (i != len - 1 && num[i] < num[i + 1]) {
13                 dropIndex = i;
14                 break;
15             }
16         }
17         
18         // replace the drop index.
19         if (dropIndex != -1) {
20             for (int i = len - 1; i >= 0; i--) {
21                 if (num[i] > num[dropIndex]) {
22                     swap(num, dropIndex, i);
23                     break;
24                 }
25             }    
26         }
27         
28         // reverse the link.
29         int l = dropIndex + 1;
30         int r = len - 1;        
31         while (l < r) {
32             swap(num, l, r);
33             l++;
34             r--;
35         }
36     }
37     
38     public void swap(int[] num, int l, int r) {
39         int tmp = num[l];
40         num[l] = num[r];
41         num[r] = tmp;
42     }
43     
44 }
View Code

SOLUTION 2:

https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/permutation/NextPermutation.java

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值