【Leetcode】496. Next Greater Element I

寻找子集的下一个更大元素
本文介绍了一种使用HashMap解决LeetCode上一道题目的方法,该题目要求找到数组子集中每个元素在父数组中对应位置后方的第一个更大元素。通过预先遍历并存储父数组的元素及其位置,再对子数组进行查找,从而高效地解决问题。

题目:

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.

注意:

  1. 这个破题目我真的读了好几遍,就是说子集的元素比如1,在nums2里面出现的位置,之后有没有比他大的。!
    2.思路就是用hashmap,先遍历和保存一下nums2。和他的位置。然后在输入nums1的值,就得到了位置,从这个点开始往后循环。如果比他大就break并且记录。如果等于长度说明没有比他大的,就返回-1。

Code:

public int[] nextGreaterElement(int[] nums1, int[] nums2) {

int len1 = nums1.length;
int len2 = nums2.length;
 int [] res = new int [len1];   
Map<Integer,Integer> map = new HashMap<Integer,Integer>();    
for(int i=0;i<len2;i++){
    map.put(nums2[i],i);
}    

    for(int j=0;j<len1;j++){
        int n = map.get(nums1[j]);
        for(;n<len2;n++){
            if(nums1[j]<nums2[n])
                break;
        }          
    res[j] = n==len2?-1:nums2[n];  
    }   return res;     
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值