LEET CODE-Next Permutation(JAVA)

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

求全排列的下一個序列

結題思路:從後往前,找到第一個降序的位置n,將n之後的數字翻轉,並將位置n-1的數字與之後的第一個比它大得出數字交換即可。

class Solution {
    public void nextPermutation(int[] nums) {
        int n = nums.length;
        if(n < 2) {
            return;
        }
        
        int right = n-1;
        while(right > 0) {
            if(nums[right -1] < nums[right]) {
                break;
            }
            right--;
        }
        
        int l = right;
        int r = n-1;
        while(l < r) {
            int temp = nums[l];
            nums[l]=nums[r];
            nums[r]= temp;
            l++;
            r--;
        }
        if(right == 0) {
            return;
        }
        int next = nums[right - 1];
        for(int i = right; i < n ; i++) {
            if(nums[i] > next) {
                nums[right - 1] = nums[i];
                nums[i] = next;
                break;
            }
        }
        
    }
}```

發佈了51 篇原創文章 · 獲贊 3 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章