Monday, November 23, 2015

[leetcode]Next permutation

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public class Solution {
    public void nextPermutation(int[] nums) {
        if (nums == null || nums.length == 1) return;
        int prev = nums.length-1;
        for (int i = nums.length-2; i >= 0&&nums[i]>=nums[prev]; prev = i, i--);
        prev--;
        int bigger = nums.length-1;
        if (prev != -1){
            while (bigger > prev && nums[bigger] <= nums[prev]){
                bigger--;
            }
            swap(nums, bigger, prev);
        }
        reverseArray(nums, prev+1, nums.length-1);
    }

    private void swap(int[]nums, int index1, int index2){
        int temp = nums[index1];
        nums[index1] = nums[index2];
        nums[index2] = temp;
    }

    private void reverseArray(int[]nums, int start, int end){
        int left = start;
        int right = end;
        while (left < right){
            swap(nums, left++, right--);
        }
    }
}

No comments:

Post a Comment