31. Next Permutation

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 and use only constant 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

题意是写出“下一个全排列”。

解法一:从后往前遍历,找出分界点。

把swap和reverseSort单独写成method。

O(n)

class Solution {
    public void nextPermutation(int[] nums) {
        int l = nums.length;
        if(l < 1) return;
        int index = l-1;
        while(index > 0) {
            if(nums[index-1] < nums[index]){
                break;
            }
            index--;
        }
        if(index == 0){
            reverseSort(nums,0,l-1);
            return;
        }else{
            int val = nums[index-1];
            int j = l-1;
            while(j>=index){
                if(nums[j]>val) break;
                j--;
            }
            swap(nums,index-1,j);
            reverseSort(nums,index,l-1);
        }
        
    }
    
    public void swap(int[] nums, int a, int b) {
        int t = nums[a];
        nums[a] = nums[b];
        nums[b] = t;
    }
    public void reverseSort(int[] nums, int a, int b){
        if(a>=b) return;
        for(int i = a; i <= (a+b)/2; i++) {
            swap(nums,i,a+b-i);
        }
    }
}

 

posted @ 2019-02-21 17:51  JamieLiu  阅读(90)  评论(0编辑  收藏  举报