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 }


  • 相关阅读:
    A3纸双面打印对折页设置方法
    BAD SYSTEM CONFIG INFO蓝屏解决办法
    局域网内Win7系统怎么开启远程桌面
    word批量删除换行符
    excel复制到word,表格格式错乱解决办法
    word取消回车自动编号
    被深信服上网行为管理器AC拒绝的操作如何正常访问
    震旦AD248复印机如何复印身份证正反面
    Win10开机后黑屏需强制关机再开机才能进桌面怎么办
    Windows已经发现此文件有一个问题
  • 原文地址:https://www.cnblogs.com/real1587/p/9955752.html
Copyright © 2011-2022 走看看