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

LeetCode-31 Next Permutation

时间:2015-02-25 11:34:39      阅读:160      评论: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

 

思路: 题目要求按照字典序求给定排列的下一个排列,如果没有,返回给定数组的最小排列。

从i=num.length-1开始往数组0遍历,如果是递增序列,继续向前,否则记录当前位置为position。

从i=num.length-1开始往数组position+1遍历,遇到第一个大于num[position]的元素,则交换两个位置的元素。

从position+1到num.length-1的元素是一个递减序列,直接将该范围的数组反转即可。

代码如下:

 1 public void nextPermutation(int[] num) {
 2         if(num == null || num.length < 2)
 3             return;
 4         
 5         int position = num.length-2;
 6         for(; position>=0; position--) {
 7             if(num[position] < num[position+1]) 
 8                 break;
 9         }
10         if(position < 0) {
11             reverse(num, 0, num.length-1);
12         } else {
13             int replace = num.length-1;
14             for(; replace>position; replace--) {
15                 if(num[replace] > num[position]) {
16                     int tmp = num[replace];
17                     num[replace] = num[position];
18                     num[position] = tmp;
19                     break;
20                 }
21             }
22             reverse(num, position+1, num.length-1);
23         }
24     }
25     
26     public int[] reverse(int[] num, int start, int over) {
27         int tmp;
28         while(start < over) {
29             tmp = num[start];
30             num[start] = num[over];
31             num[over] = tmp;
32             start++;
33             over--;
34         }
35         return num;
36     }

 

LeetCode-31 Next Permutation

标签:

原文地址:http://www.cnblogs.com/linxiong/p/4299330.html

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