下一个更大的数 I

你有两个数组 nums1nums2(互不重复),其中nums1nums2的子集。 在nums2的相应位置找到nums1所有元素的下一个更大数字。

nums1中的数字x的下一个更大数字是nums2中x右边第一个更大的数字。 如果它不存在,则为此数字输出-1。

样例

例子 1:

输入: nums1 = [4,1,2], nums2 = [1,3,4,2].
输出: [-1,3,-1]
解释:
     对于第一个数组中的数字4,在第二个数组中找不到下一个更大的数字,因此输出-1。
     对于第一个数组中的数字1,第二个数组中的下一个更大数字是3。
     对于第一个数组中的数字2,第二个数组中没有下一个更大的数字,因此输出-1。

例子 2:

输入: nums1 = [2,4], nums2 = [1,2,3,4].
输出: [3,-1]
解释:
     对于第一个数组中的数字2,第二个数组中的下一个更大数字是3。
     对于第一个数组中的数字4,第二个数组中没有下一个更大的数字,因此输出-1。

注意事项

1.nums1nums2中的所有数字都是唯一的。
2.nums1nums2的长度不超过1000。

 

 

class Solution {
public:
    /**
     * @param nums1: an array
     * @param nums2: an array
     * @return:  find all the next greater numbers for nums1's elements in the corresponding places of nums2
     */
    map<int, int> mymap;
    vector<int> nextGreaterElement(vector<int> &nums2, vector<int> &nums1)
    {
        // Write your code here
        for(int i = nums1.size() - 1; i >= 0; i--)
        {
            int index  = -1;
            for(int j = i + 1; j < nums1.size(); j++)
            {
                if(nums1[j] > nums1[i])
                {
                    index = j;
                    break;
                }
            }
            if(index != -1)
                mymap[nums1[i]] = nums1[index];
            else
            {
                mymap[nums1[i]] = -1;
            }
        }
        for(int i = 0; i < nums2.size(); i++)
        {
            nums2[i]  = mymap[nums2[i]];
        }
        return nums2;
    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值