LeetCode 496. Next Greater Element I

    xiaoxiao2021-03-25  86

    496. Next Greater Element I

    Description You are given two arrays (without duplicates) nums1 and nums2 where nums1’s elements are subset of nums2. Find all the next greater numbers for nums1’s elements in the corresponding places of nums2.

    The Next Greater Number of a number x in nums1 is the first greater number to its right in nums2. If it does not exist, output -1 for this number.

    Example 1: Input: nums1 = [4,1,2], nums2 = [1,3,4,2]. Output: [-1,3,-1] Explanation: For number 4 in the first array, you cannot find the next greater number for it in the second array, so output -1. For number 1 in the first array, the next greater number for it in the second array is 3. For number 2 in the first array, there is no next greater number for it in the second array, so output -1. Example 2: Input: nums1 = [2,4], nums2 = [1,2,3,4]. Output: [3,-1] Explanation: For number 2 in the first array, the next greater number for it in the second array is 3. For number 4 in the first array, there is no next greater number for it in the second array, so output -1. Note: All elements in nums1 and nums2 are unique. The length of both nums1 and nums2 would not exceed 1000.

    Analysis 这道题的意思是寻找在子集中的每一个数在集合中的右边顺序第一位比它大的数字,如果没有则返回就返回-1。我的做法是先将子集中元素在集合中的位置找出来,然后从该位置下标加一开始寻找比它大的第一个数,若找到最后一个不存在则返回-1。

    Code

    class Solution { public: vector<int> nextGreaterElement(vector<int>& findNums, vector<int>& nums) { int len = findNums.size(); int len2 = nums.size(); int index; vector<int> vec; for(int i = 0 ;i <len;++i){ for(int j = 0 ; j <len2;++j){ if(findNums[i] == nums[j]){ index = j; break; } } for(int k = index+1 ; k <=len2 ; ++k){ if(k == len2) { vec.push_back(-1); break; } if(nums[k]>findNums[i]){ vec.push_back(nums[k]); break; } } } return vec; } };
    转载请注明原文地址: https://ju.6miu.com/read-26501.html

    最新回复(0)