当前位置:网站首页>Leetcode-31: next spread

Leetcode-31: next spread

2022-07-05 06:09:00 Chrysanthemum headed bat

subject

Topic linking
An integer array array Is to arrange all its members in sequence or linear order .

  • for example ,arr = [1,2,3] , The following can be regarded as arr Permutation :[1,2,3]、[1,3,2]、[3,1,2]、[2,3,1] .

Integer array Next spread It refers to the next lexicographic order of its integers . More formally , Arrange all the containers in the order from small to large , So the array of Next spread It is the arrangement behind it in this ordered container . If there is no next larger arrangement , Then the array must be rearranged to the lowest order in the dictionary ( namely , Its elements are arranged in ascending order ).

  • for example ,arr = [1,2,3] The next line up for is [1,3,2] .
  • Similarly ,arr = [2,3,1] The next line up for is [3,1,2] .
  • and arr = [3,2,1] The next line up for is [1,2,3] , because [3,2,1] There is no greater order of dictionaries .
    Give you an array of integers nums , find nums The next permutation of .

must In situ modify , Only additional constant spaces are allowed .

Example 1:

 Input :nums = [1,2,3]
 Output :[1,3,2]

Example 2:

 Input :nums = [3,2,1]
 Output :[1,2,3]

Example 3:

 Input :nums = [1,1,5]
 Output :[1,5,1]

Problem solving

Method 1 :

Reference link

  1. With 12385764 As an example , Because you want to find the next bigger , So we need to traverse in reverse order .
  2. Reverse traversal , Find the first incremental adjacent element 57 ( Therefore, the following elements must be decreasing ,764)
  3. However, we cannot directly let 5 and 7 swapping , Rather let 5 and 6 In exchange for . So we can traverse in reverse order to find the first ratio 5 Big elements , yes 6
  4. After the exchange, it became 12386754, However, this is not the next larger element you want ( But there are several elements below ). So sort the latter part 12386 754---->12386 457
class Solution {
    
public:
    void nextPermutation(vector<int>& nums) {
    
        int n=nums.size();
        int i=n-2,j=n-1;
        while(i>=0&&nums[i]>=nums[j]){
    
            i--;
            j--;
        }

        int k=n-1;
        if(i>=0){
    
            while(nums[i]>=nums[k]) k--;
            swap(nums[i],nums[k]);
        }
        sort(nums.begin()+i+1,nums.end());
    }
};
原网站

版权声明
本文为[Chrysanthemum headed bat]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/186/202207050546085853.html