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 }


  • 相关阅读:
    iOS 音频视频图像合成那点事
    Android低功耗蓝牙(BLE)使用详解
    android实现超酷的腾讯视频首页和垂直水平网格瀑布流一揽子效果
    基于vue单页应用的例子
    Android 6.0 超级简单的权限申请 (Permission)
    ubuntu创建Centos7镜像&&配置运行环境
    Scikit-learn方法使用总结
    解决TensorFlow最新代码编译错误问题
    jQuery 基础
    数据交换格式 —— JSON(JavaScript Object Notation)
  • 原文地址:https://www.cnblogs.com/real1587/p/9955752.html
Copyright © 2011-2022 走看看