496. Next Greater Element I
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:
- All elements in
nums1
andnums2
are unique. - The length of both
nums1
andnums2
would not exceed 1000.
刚开始看了好久没搞懂题意。。。尤其是第一个案例蒙圈了,觉得第一个案例应该输出[-1,3,4]才对。。。后面终于看懂题目什么意思了,首先在第二个案例里面找到跟第一个案例要查找的数字相同的数,然后往第二个数组里面这个数的右边找大于这个数的第一个数,这么一来问题就好解决了。
1 /** 2 * Return an array of size *returnSize. 3 * Note: The returned array must be malloced, assume caller calls free(). 4 */ 5 int* nextGreaterElement(int* findNums, int findNumsSize, int* nums, int numsSize, int* returnSize) { 6 int *answer = (int *)malloc(sizeof(int) * findNumsSize); 7 *returnSize = findNumsSize; 8 memset(answer,-1,sizeof(int) * findNumsSize); 9 int flag; 10 for(int i=0;i<findNumsSize;i++) { 11 flag = 0; 12 for(int j=0;j<numsSize;j++) { 13 if(flag == 1){ 14 if(findNums[i] < nums[j]){ 15 answer[i] = nums[j]; 16 break; 17 } 18 } 19 if(findNums[i] == nums[j]) flag = 1; 20 } 21 } 22 return answer; 23 }