LeetCode刷题笔记-496.下一个更大元素 I

LeetCode刷题笔记-496.下一个更大元素 I

C代码

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */ 
struct hmap_st {
    int key;
    int value;
    int index;
    UT_hash_handle hh;
};
void push(int *stack, int *top, int val) {
    (*top)++;
    stack[(*top)] = val;
}

int pop(int *stack, int *top) {
    int ret = -1;
    if(*top < 0)
        return ret;
    ret = stack[(*top)];
    (*top)--;
    return ret;
}
int* nextGreaterElement(int* nums1, int nums1Size, int* nums2, int nums2Size, int* returnSize){
    struct hmap_st *hmap = NULL;
    struct hmap_st *t = NULL;
    struct hmap_st *tmp = NULL;
    int stack[1024] = {0};
    int top = -1;
    int i;
    int tp;

    int *ret = NULL;

    *returnSize = nums1Size;
    ret = calloc(nums1Size, sizeof(int));


    for (i = 0; i < nums1Size; i++) {
        t = calloc(1, sizeof(*t));
        t->key = nums1[i];
        t->value = -1;
        t->index = i;
        HASH_ADD_INT(hmap, key, t);
    }

    for (i = nums2Size - 1; i >= 0; i--) {
        if (top == -1) {
            push(stack, &top, nums2[i]);
            continue;
        }
        while (nums2[i] > stack[top]) {
            tp = pop(stack, &top);
            if(top == -1)
                break;
            HASH_FIND_INT(hmap, &tp, t);
            if (t == NULL)
                break;
            t->value = stack[top];
        }
        push(stack, &top, nums2[i]);
    }

    for (i = top; i > 0; i--) {
        HASH_FIND_INT(hmap, &stack[i], t);
        if(t == NULL)
            continue;
        t->value = stack[i-1]; 
    }

    HASH_ITER(hh, hmap, t, tmp) {
        ret[t->index] = t->value;
    }

    return ret;
}

注意点

  1. 主题思路右边最大的第一个,需要使用到单调栈;
  2. 注意最后遍历栈的处理,如果遇到不在num1[]的元素需要continue而不是break停止了后面的赋值;
  3. 注意处理stack弹出的元素避免遗漏场景;

结果

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值