LeetCode 496: Next Greater Element I (下一个大的元素)

本文介绍两种方法解决寻找数组中下一个更大元素的问题。一种是通过迭代器查找并对比大小,另一种利用栈与哈希表提高效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

给定两个列表(元素不重复)nums1和nums2,其中nums1是nums2的子集。查找nums1中每个元素nums1[i]在nums中的下一个大的元素(位于nums1[i]在nums2中对应位置的右方)。如果存在,则返回下一个大的元素;如果不存在,返回-1.

Example 1:


Example 2:


实现一:

使用迭代器iterator,使用find()函数查找nums1中元素在nums2中的位置,并使用distance()函数返回位置,然后再返回位置的右边查找下一个大的元素。注:使用STL的vector时,可以利用函数 max_element,min_element,distance可以获取Vector中最大、最小值的值和位置索引,如下:

int main{
    std::vector<double> v {1.0, 2.0, 3.0, 4.0, 5.0, 1.0, 2.0, 3.0, 4.0, 5.0};  
    std::vector<double>::iterator biggest = std::max_element(std::begin(v), std::end(v));  
    std::cout << "Max element is " << *biggest<< " at position " << std::distance(std::begin(v), biggest) << std::endl;
    return 0;
}     

Code:

class Solution {
public:
    vector<int> nextGreaterElement(vector<int>& findNums, vector<int>& nums) {
        int n = findNums.size();
        vector<int>::iterator it;
        vector<int> NGE(n);
        for(int i=0; i<n; i++){
            it = find(nums.begin(),nums.end(),findNums[i]);
            int j = distance(nums.begin(),it)+1;
            for(j; j<nums.size(); j++){
                if(nums[j]>findNums[i]){
                    NGE[i]=nums[j];
                    break;
                } 
            }
            if(j==nums.size()) NGE[i]=-1;
        }
        return NGE;
    }
};

实现二:

使用stack+unordered_map,因为nums1是nums2的子集,所以要找nums1中元素在nums2中的“下一个大的元素”,只需要对nums2中元素建立<当前元素,下一个大的元素>对应关系。使用unordered_map<int, int> m来存放对应关系,使用stack来帮助建立对应关系。m.count()返回匹配给定主键的元素的个数。

Code:

class Solution {
public:
    vector<int> nextGreaterElement(vector<int>& findNums, vector<int>& nums) {
        stack<int> s;
        unordered_map<int, int> m;
        for (int n : nums) {
            while (s.size() && s.top() < n) {
                m[s.top()] = n;
                s.pop();
            }
            s.push(n);
        }
        vector<int> ans;
        for (int n : findNums) ans.push_back(m.count(n) ? m[n] : -1);
        return ans;
    }
};





评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值