LeetCode Next Permutation -电脑资料

电脑资料 时间:2019-01-01 我要投稿
【www.unjs.com - 电脑资料】

    题目描述:

    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

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

LeetCode Next Permutation

    思路:

    将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] 的数逆置,

电脑资料

LeetCode Next Permutation》(https://www.unjs.com)。

    实现代码:

   

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--;    	}    }}

最新文章