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

LeetCode:Next Permutation

时间:2016-07-01 16:27:02      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:

Next Permutation




Total Accepted: 70533 Total Submissions: 261357 Difficulty: Medium

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

Subscribe to see which companies asked this question

Hide Tags
 Array























思路:

下一个排列数,定义:比当前数大的最小数。

1.从左往右找到第一个“顺”,即nums[i-1] <nums[i],因此nums[i,n-1]都是“逆序”;

2.从定义可知,我们要从[i,n-1]中找一个最小的数与nums[i-1]交往,然后将nums[i,n-1]“顺序”排序即可。

如:nums = [6,2,5,4,3,1], n = 6;

由1)找到i = 2,nums[2,5] = [5,4,3,1]是“逆序”;

由2)交换后得 nums=[6,3,5,4,2,1],再将[i, n-1]顺序,得解[6,3,1,2,4,5];

由于[i, n-1]已是逆序,直接逆序就变成“顺序”,时间O(n),即总时间O(n);


java code:

public class Solution {
    public void nextPermutation(int[] nums) {
        
        int n = nums.length;
        int i = n-1;
        // 从左到右,找到第一个“顺序”位置
        while(i > 0) {
            if(nums[i-1] < nums[i]) break;
            i--;
        }
        
        if(i==0) {
            reverse(nums, 0, n-1);
            return;
        }
        
        // 找到第一个大于i位置值的下标j,并与i位置值交换
        int j = n-1;
        int val = nums[i-1];
        while(i < j && val >= nums[j]) j--;
        swap(nums, i-1, j);
        // 逆序[i,n-1]部分
        reverse(nums, i, n-1);
        
    }
    
    // 自定义函数:逆序
    void reverse(int[] nums, int lo, int hi) {
        while(lo < hi) {
            swap(nums, lo, hi);
            lo++;hi--;
        }
    }
    // 交换
    void swap(int[] nums, int lo, int hi) {
        nums[lo] ^= nums[hi];
        nums[hi] ^= nums[lo];
        nums[lo] ^= nums[hi];
    }
}


LeetCode:Next Permutation

标签:

原文地址:http://blog.csdn.net/itismelzp/article/details/51800293

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