496. Next Greater Element I(C语言)

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.

Example 1:

Input: nums1 = [4,1,2], nums2 = [1,3,4,2].
Output: [-1,3,-1]
Explanation:
    For number 4 in the first array, you cannot find the next greater number for it in the second array, so output -1.
    For number 1 in the first array, the next greater number for it in the second array is 3.
    For number 2 in the first array, there is no next greater number for it in the second array, so output -1.

Example 2:

Input: nums1 = [2,4], nums2 = [1,2,3,4].
Output: [3,-1]
Explanation:
    For number 2 in the first array, the next greater number for it in the second array is 3.
    For number 4 in the first array, there is no next greater number for it in the second array, so output -1.

Note:

  1. All elements in nums1 and nums2 are unique.
  2. The length of both nums1 and nums2 would not exceed 1000.

/**
 * Return an array of size *returnSize.
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* nextGreaterElement(int* findNums, int findNumsSize, int* nums, int numsSize, int* returnSize) {
    
    int i=0;
    int l=0;//记录num1的下标
    int temp=0;//存放在num2中与num1值相同的数的下标
    int* result = (int*)malloc(findNumsSize * sizeof(int));
    *returnSize = findNumsSize;
    //全部初始化为-1
    for(i=0;i<*returnSize;i++){
        result[i]=-1;
    }
    //用while循环num1数组,在num2数组中找到这个数
    while(ltemp)&(nums[i]>findNums[l])){
                result[l]=nums[i];
                break;
            }
         
        }
         l++;
    }
    return result;
}
花了我2h的时间弄这个问题 哈哈哈哈 13点了还好我没放弃
tips:
1.要新建一个放结果的数组,并且定义长度
int* result = (int*)malloc(findNumsSize * sizeof(int));
    *returnSize = findNumsSize;

2. *returnSize里面是数组长度,returnSize是指针,我一开始for循环里面写的returnSize,一直显示超时,expect result里什么也没有
for(i=0;i<*returnSize;i++){
        result[i]=-1;
    }
3.for循环里面的if语句里面的break,直接就跳出for循环了,不会再执行for循环,要是想跳过后面的语句,进入下一次for循环的话用continue
4.把l++和temp=returnSize放了对的位置.....不过柏宁说我这样多了很多次比较,让我看看别人的结果 哈哈哈 吃饭去了

你可能感兴趣的:(496. Next Greater Element I(C语言))