当前位置:网站首页>【Hot100】31. Next spread

【Hot100】31. Next spread

2022-07-04 17:47:00 Wang Liuliu's it daily

31. Next spread

Medium question
Integer array Next spread It refers to the next lexicographic order of its integers .

Their thinking :

  • Find the first element smaller than the following
  • Exchange with the following minimum value larger than it
  • After the exchange, the numbers behind him are arranged in ascending order , reverse that will do , because 1. Characteristics of , The following is in descending order
class Solution {
    
    public void nextPermutation(int[] nums) {
    
        int pre = nums.length - 2;
        while (pre >= 0 && nums[pre] >= nums[pre + 1]) pre--;
        if (pre == -1) reverse(nums, 0, nums.length - 1); //  Boundary value processing 
        else {
    
            int post = pre + 1;
            while (post < nums.length && nums[post] > nums[pre]) post++;
            post--;
            int t = nums[pre];
            nums[pre] = nums[post];
            nums[post] = t;
            reverse(nums, pre + 1, nums.length - 1);
        }
    }
    void reverse(int[] nums, int l, int r) {
    
        while (l < r) {
    
            int t = nums[l];
            nums[l++] = nums[r];
            nums[r--] = t; 
        }
    }
}
原网站

版权声明
本文为[Wang Liuliu's it daily]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/185/202207041602494863.html