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

[LeetCode] 31. Next Permutation ☆☆☆

时间:2017-02-21 15:56:38      阅读:213      评论:0      收藏:0      [点我收藏+]

标签:观察   ica   算法   round   put   wap   第一个   ogr   .net   

 

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

 

解法:

  这道题要求下一个排列顺序,也就是全排列中的下一个(如:123的全排列为123、132、213、231、312、321,给定其中一个,输出其下一个),如果给定数组是降序,则说明是全排列的最后一种情况,则下一个排列就是最初始情况,全排列知识可以参见:全排列生成算法:next_permutation。我们再来看下面一个例子,有如下的一个数组

1  2  7  4  3  1

下一个排列为:

1  3  1  2  4  7

那么是如何得到的呢,我们通过观察原数组可以发现,如果从末尾往前看,数字逐渐变大,到了2时才减小的,然后我们再从后往前找第一个比2大的数字,是3,那么我们交换2和3,再把此时3后面的所有数字转置一下即可,步骤如下:

1  2  7  4  3  1

1  2  7  4  3  1

1  3  7  4  2  1

1  3  1  2  4  7

public class Solution {
    public void nextPermutation(int[] nums) {
        if (nums == null || nums.length == 0) {
            return;
        }
        int index = nums.length - 2;
        for (; index >= 0; index--) {
            if (nums[index] < nums[index + 1]) {
                break;
            }
        }
        if (index == -1) {
            Arrays.sort(nums);
            return;
        }
        
        int biggerIndex = nums.length - 1;
        for (; biggerIndex >= 0; biggerIndex--) {
            if (nums[biggerIndex] > nums[index]) {
                break;
            }
        }
        
        swap(nums, index, biggerIndex);
        reverse(nums, index + 1, nums.length - 1);
    }
    
    public void swap(int[] num, int i, int j) {
        int temp = num[i];
        num[i] = num[j];
        num[j] = temp;
    }
    
    public void reverse(int[] num, int begin, int end) {
        for (int i = begin, j = end; i < j; i++, j--) {
            swap(num, i, j);
        }
    }
}

 

[LeetCode] 31. Next Permutation ☆☆☆

标签:观察   ica   算法   round   put   wap   第一个   ogr   .net   

原文地址:http://www.cnblogs.com/strugglion/p/6424191.html

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