LeetCode-Next Greater Element I

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_24133491/article/details/83021577

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.

题意:给定两个数组nums1和nums2,其中nums1是nums2的子数组;现在要求找出nums1中所有的元素在nums2对应位置处的下一个比此元素大的元素,如果没有,则返回-1;

解法:要在nums2中找到比当前元素大的那个元素,我们首先需要做的是定位nums1中的当前元素在nums2中的位置,可以利用哈希表存储nums2中元素及其下标的键值对;这样,遍历nums1中的每个元素,可以立刻找到在nums2中的位置,从这个位置之后再开始找比当前元素大的那个元素;

Java
class Solution {
    public int[] nextGreaterElement(int[] nums1, int[] nums2) {
        Map<Integer, Integer> indexs = new HashMap<>();
        int[] result = new int[nums1.length];
        for (int i = 0; i < nums2.length; i++) indexs.put(nums2[i], i);
        for (int i = 0; i < nums1.length; i++) {
            int index = -1;
            for (int j = indexs.get(nums1[i]) + 1; j < nums2.length; j++) {
                if (nums2[j] > nums1[i]) {
                    index = j;
                    break;
                }
            }
            result[i] = index == -1 ? index : nums2[index];
        }
        return result;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_24133491/article/details/83021577