/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* nextGreaterElement(int* nums1, int nums1Size, int* nums2, int nums2Size, int* returnSize){
int *ans = (int *)malloc(sizeof(int)*1000);
memset(ans,-1,sizeof(int)*nums1Size);//memset初始化函数,将某一块内存中的内容全部设置为指定的值
//定义哈希数组
int hash[10000];
memset(hash,-1,sizeof(int)*10000);
//定义单调栈
int stack[nums2Size];
int top = -1;
*returnSize =nums1Size;
//将nums1中元素存在hash数组中
for(int i = 0;i < nums1Size;i++){
hash[nums1[i]] = i;
}
//遍历nums2,
for(int i = 0;i < nums2Size;i++){
while((top != -1) && (stack[top] < nums2[i])){
if(hash[stack[top]] != -1){
ans[hash[stack[top]]] = nums2[i];
}
--top;//弹出栈顶
}
stack[++top] = nums2[i];//入栈
}
return ans;
}
LeetCode:496. 下一个更大元素 I
最新推荐文章于 2024-07-25 21:51:21 发布