算法系列(18) Leetcode 496. Next Greater Element I

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:

  1. All elements in nums1 and nums2 are unique.
  2. The length of both nums1 and nums2 would not exceed 1000.
思路:这道题因为要求得第二个序列中第一个序列中数后面大于这个数的数,所以得到位置数是关键,用es6中的for...of...语句,能够达到这个效果。
之后即可对后面进行遍历查找。注意可以设置一个标签项,因为当不存在时,要返回-1.这样比较简单方便。

/**
 * @param {number[]} findNums
 * @param {number[]} nums
 * @return {number[]}
 */
var nextGreaterElement = function(findNums, nums) {
    var array = [];
    for(a of findNums){
        var bool=false;
        var b = nums.indexOf(a);
        for(var i=b+1; ia){
                array.push(nums[i]);
                bool = true;
                break;
            }
        }
        if(!bool){
            array.push(-1);
        }
    }
    return array;
};


你可能感兴趣的:(算法)