• 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 }


  • 相关阅读:
    Struts2.1.8 + Spring3.0+ Hibernate3.2整合笔记
    SSH整合之_架构的历史序列图
    Spring整合Hibernate笔记
    Oracle日志文件的管理与查看
    java调用Oracle存储存储过程
    Oracle PLSQL笔记(过程的创建和及调用)
    使用 Spring 2.5 TestContext 测试DAO层
    SpringBoot 启动慢的解决办法
    C++ CEF 浏览器中显示 Tooltip(标签中的 title 属性)
    Chromium CEF 2623 -- 支持 xp 的最后一个版本源码下载和编译步骤
  • 原文地址:https://www.cnblogs.com/real1587/p/9955752.html
Copyright © 2020-2023  润新知