lintode(52)下一个排列

来源:互联网 发布:smali语法编程 编辑:程序博客网 时间:2024/04/30 14:03

描述:

给定一个整数数组来表示排列,找出其之后的一个排列。

 注意事项

排列中可能包含重复的整数


样例:

给出排列[1,3,2,3],其下一个排列是[1,3,3,2]

给出排列[4,3,2,1],其下一个排列是[1,2,3,4]


思路 :

找出第一个(i-1)>(i)的点,然后找出比nums[i-1]大且最接近的值,和其交换位置,然后对后面的序列进行排序

public class Solution {    /**     * @param nums: an array of integers     * @return: An array of integers that's next permuation     */    public int[] nextPermutation(int[] nums) {        // write your code here        if(nums == null || nums.length == 0 || nums.length == 1){            return nums;        }                int len = nums.length;        int flag = len - 1;        boolean change = false;        for(int i = len - 1;i>=1;i--){            if(nums[i] > nums[i-1]){                flag = i;                change = true;                break;            }        }                if(!change){            Arrays.sort(nums);            return nums;        }        int temp = nums[flag];        nums[flag] = nums[flag - 1];        for(int i = flag;i<len;i++){            if(nums[i] > nums[flag - 1] && nums[i] < temp){                int p = temp;                temp = nums[i];                nums[i] = p;            }        }        nums[flag - 1] = temp;        for(int i = flag;i<len;i++){            for(int j = i+1;j<len;j++){                if(nums[j]<nums[i]){                    int m = nums[i];                    nums[i] = nums[j];                    nums[j] = m;                }            }        }        return nums;    }}


0 0
原创粉丝点击