LeetCode -- Next Permutation

来源:互联网 发布:日本文化史知乎 编辑:程序博客网 时间:2024/05/29 15:32
题目描述:


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


1 0