Find the method to buckle 496 the next bigger element I

496 The next larger element I is
given two arrays nums1 and nums2 without repeated elements, where nums1 is a subset of nums2. Find the next greater value of each element in nums1 in nums2.

The next greater element of the number x in nums1 refers to the first element greater than x to the right of the corresponding position in nums2. If it does not exist, the corresponding position outputs -1.

Example 1:

enter:

nums1 = [4,1,2], nums2 = [1,3,4,2].

Output:

 [-1,3,-1]

Explanation:

For the number 4 in num1, you cannot find the next higher number in the second array, so -1 is output.
For the number 1 in num1, the next larger number to the right of the number 1 in the second array is 3.
For the number 2 in num1, there is no next higher number in the second array, so -1 is output.

Example 2:

enter:

nums1 = [2,4], nums2 = [1,2,3,4].

Output:

[3,-1]

Explanation:

For the number 2 in num1, the next larger number in the second array is 3.
For the number 4 in num1, there is no next higher number in the second array, so -1 is output.

prompt:

  • All elements in nums1 and nums2 are unique.
  • The array size of nums1 and nums2 is not more than 1000.

Idea:
Use the find method to directly find the corresponding number in nums1 in nums2 (because nums1 is a subset of nums2, so it can definitely be found), and then find the next number larger than him.
Code:

class Solution
{
    
    
public:
    vector<int> nextGreaterElement(vector<int> &nums1, vector<int> &nums2)
    {
    
    
        vector<int> ans;
        for (int i = 0; i < nums1.size(); i++)
        {
    
    
            auto iter = find(nums2.begin(), nums2.end(), nums1[i]);
            for (iter = iter + 1; iter != nums2.end(); iter++)
            {
    
    
                if (*iter > nums1[i])
                {
    
    
                    ans.push_back(*iter);
                    break;
                }
            }
            if (iter == nums2.end())
                ans.push_back(-1);
        }
        return ans;
    }
};

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_46039856/article/details/108213947