zoukankan      html  css  js  c++  java
  • 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:

    1. All elements in nums1 and nums2 are unique.
    2. The length of both nums1 and nums2 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 }


  • 相关阅读:
    WSL下的Ubuntu 18.04LTS配置软件源和系统更新
    宝塔 5.9.2 最终版 专业版
    宝塔面板7.2.0学习版集合--包含(专业版、企业版及部分插件)
    网络安全学习和CTF必不可少的一些网站
    Hello Blog !
    如何解决机器学习树集成模型的解释性问题
    机器学习建模老司机的几点思考与总结
    2019 秋招提前批蘑菇街一面面经(带答案)
    Java 最全异常讲解
    Spring Context 你真的懂了吗
  • 原文地址:https://www.cnblogs.com/real1587/p/9955752.html
Copyright © 2011-2022 走看看