LeetCode 31. Next Permutation

原题链接在这里:https://leetcode.com/problems/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

题解:

参考了这篇博文:http://blog.csdn.net/linhuanmars/article/details/20434115

分两种情况:

1. 从前往后一路数值一直变小,如"654321", 返回的应该是"123456"也就是整个反转

2. 数值没有一直变下,如"236541", 此时从后往前找到第一个数值下降的点3<6, 找到3,记下index i,

然后从末位到3找到第一个比3大的数字, 这里是4. swap nums[i] and nums[j]. 变成"246531"

最后反转 i 后面的部分, 得到"241356".

Note: 找i的时候是 nums[i] >= nums[i+1] 等于时也往前移动i, 只有小于时才停下.

Time Complexity: O(nums.length).

Space: O(1).

AC Java:

 1 class Solution {
 2     public void nextPermutation(int[] nums) {
 3         //以2,3,6,5,4,1为例
 4         //从后往前,找到第一个变小的的数字,如3
 5         //从末位到3找到第一个比3大的数字, 这里是4
 6         //调换3 和 4, 然后反转 调换后 4后面的数字
 7         if(nums == null || nums.length == 0){
 8             return;
 9         }
10         
11         int i = nums.length-2;
12         while(i>=0 && nums[i]>=nums[i+1]){
13             i--;
14         }
15         
16         if(i>=0){
17             int j = nums.length-1;
18             while(nums[j] <= nums[i]){
19                 j--;
20             }
21             swap(nums, i, j);
22         }
23         
24         reverse(nums, i+1, nums.length-1);
25     }
26     
27     private void reverse(int [] nums, int i, int j){
28         while(i<j){
29             swap(nums, i++, j--);
30         }
31     }
32     
33     private void swap(int [] nums, int i, int j){
34         int temp = nums[i];
35         nums[i] = nums[j];
36         nums[j] = temp;
37     }
38 }

类似Next Greater Element IIIPrevious Permutation With One SwapIterator for Combination.

跟上Next Palindrome Using Same Digits.

posted @ 2015-10-01 21:18  Dylan_Java_NYC  阅读(334)  评论(0编辑  收藏  举报