LeetCode--No.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
 

這道題有點進步,至少知道提交之前多跑幾個自己嘗試的test case, 然後test case還是設計不全面,導致了一次錯誤提交。再有一個問題就是,寫代碼之前,邏輯沒有想太明白,以至於有邏輯錯誤在裏面。

Arrays.sort(nums, start, end+1) 這個排序函數可以用來排序subarray, 挺好用的,希望能記住。

 

class Solution {
    public void nextPermutation(int[] nums) {
        if (nums == null || nums.length == 0)   return;
        int i = nums.length - 1;
        while(i > 0){
            if (nums[i] > nums[i-1]){
                break;
            }
            else{
                i--;
            }
        }
        if (i > 0){
            int min = Integer.MAX_VALUE;
            int min_index = 0;
            for(int j = i; j < nums.length; j++){
                if (nums[j] > nums[i-1] && nums[j] < min){
                    min = nums[j];
                    min_index = j;
                }
            }
            int tmp = nums[i-1];
            nums[i-1] = nums[min_index];
            nums[min_index] = tmp;
        }
        Arrays.sort(nums, i, nums.length);
        return;
    }
}

年齡大了開始聽陳綺貞了,哎,神奇。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章