leetcode 496. 下一个更大元素 I(next greater element i)C语言

leetcode 496. 下一个更大元素 I(next greater element i)C语言

1.description

https://leetcode-cn.com/problems/next-greater-element-i/

给定两个 没有重复元素 的数组 nums1 和 nums2 ,其中nums1 是 nums2 的子集。找到 nums1 中每个元素在 nums2 中的下一个比其大的值。

nums1 中数字 x 的下一个更大元素是指 x 在 nums2 中对应位置的右边的第一个比 x 大的元素。如果不存在,对应位置输出 -1 。

示例 1:

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

示例 2:

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

提示:

nums1和nums2中所有元素是唯一的。
nums1和nums2 的数组大小都不超过1000。

2.solution

#define REALLOC_STEP 1000

int* nextGreaterElement(int* nums1, int nums1Size, int* nums2, int nums2Size, int* returnSize){
    int *ans = (int*)malloc(sizeof(int)*nums1Size);
    int hashSize = 1000;
    int *hash = (int*)malloc(sizeof(int)*hashSize);
    int *stack = (int*)malloc(sizeof(int)*nums2Size);
    int top = -1;
    for(int i=nums2Size-1; i>=0; --i){
        while(top!=-1 && nums2[i]>=stack[top]){
            top--;
        }
        while(nums2[i]>=hashSize){
            hashSize += REALLOC_STEP;
            hash = (int*)realloc(hash, sizeof(int)*hashSize);
        }
        hash[nums2[i]] = top==-1 ? -1 : stack[top];
        stack[++top] = nums2[i];
    }

    for(int i=0; i<nums1Size; ++i){
        ans[i] = hash[nums1[i]];
    }

    free(hash);
    free(stack);

    *returnSize = nums1Size;

    return ans;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值