首页 > 其他 > 详细

LeetCode -- Next Permutation

时间:2015-09-22 10:21:27      阅读:234      评论: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


给定一个序列,找到下一个排序。


思路:


将index, index2 = -1;
1. 从右向左找,如果不满足 num[i+1] < num [i],index = i;
2. 再从右向左找到第一个num[i] > num[index] 的数,index 2 = i;
3. 交换num[index]和num[index2]
4. 将num[index+1... n] 的数逆置。


实现代码:




public class Solution {
    public void NextPermutation(int[] nums) {
        var index = -1;
    	for(var i = nums.Length - 1; i > 0; i--){
    		if(nums[i] > nums[i-1]){
    			index = i-1;
    			break;
    		}
    	}
    	
    	var index2 = -1;
    	if(index != -1){
    		for(var i = nums.Length - 1; i >= 0; i--){
    			if(nums[i] > nums[index]){
    				index2 = i;
    				break;
    			}
    		}
    	}
    	
    	
    	if(index != -1 && index2 != -1){
    		var t = nums[index];
    		nums[index] = nums[index2];
    		nums[index2] = t;
    	}
    	
    	var k = index + 1;
    	var j = nums.Length - 1;
    	
    	while(k < j){
    		var tmp = nums[k];
    		nums[k] = nums[j];
    		nums[j] = tmp;
    		
    		k++;
    		j--;
    	}
    }
}


版权声明:本文为博主原创文章,未经博主允许不得转载。

LeetCode -- Next Permutation

原文:http://blog.csdn.net/lan_liang/article/details/48650053

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!