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.

    题目含义:给两个数组findNums和nums,其中findNums数组是nums数组的子数组。返回一个和findNums等长的数组,其返回的内容为:对于findNums[i],返回的result[i]为nums[i]数组中,findNums[i]的后面的元素中第一个比findNums[i]大的元素。如果不存在这样的元素就写-1。

    例如

    Input: nums1 = [4,1,2], nums2 = [1,3,4,2].
    4:在nums2中4的右边找第一个大于4的数,没有找到,-1
    1:在nums2中1的右边找第一个大于1的数,3
    2:在nums2中2的右边找第一个大于2的数,没有找到,-1

     1     public int[] nextGreaterElement(int[] nums1, int[] nums2) {
     2 //        建立每个数字和其右边第一个较大数之间的映射,没有的话就是-1。
     3 // 我们遍历原数组中的所有数字,如果此时栈不为空,且栈顶元素小于当前数字,
     4 // 说明当前数字就是栈顶元素的右边第一个较大数,那么建立二者的映射,并且去除当前栈顶元素,最后将当前遍历到的数字压入栈。
     5 // 当所有数字都建立了映射,那么最后我们可以直接通过哈希表快速的找到子集合中数字的右边较大值
     6         int[] result = new int[nums1.length];
     7         Map<Integer, Integer> pairs = new HashMap<>();
     8         Stack<Integer> stack = new Stack<>();
     9         for (int number : nums2) {
    10             while (!stack.isEmpty() && stack.peek() < number) {
    11                 pairs.put(stack.pop(), number);
    12             }
    13             stack.push(number);
    14         }
    15 
    16         for (int i = 0; i < nums1.length; i++) {
    17             result[i] = pairs.getOrDefault(nums1[i], -1);
    18         }
    19         return result;        
    20     }
  • 相关阅读:
    《编程珠玑》读后感之一
    《梦断代码》读后感之三
    java项目中下载文件文件名乱码
    struts中action与页面之间的传值方式
    使用JSON数据报错和方法
    java中实现将一个数字字符串转换成逗号分隔的数字串, 即从右边开始每三个数字用逗号分隔
    java中判断一个字符在字符串中出现的次数
    使用面向对象(OO)的思想,实现循环输入多个会员的信息,根据会员编号,查找会员积分
    MySQL添加用户、删除用户与授权
    vi编辑器的使用
  • 原文地址:https://www.cnblogs.com/wzj4858/p/7725918.html
Copyright © 2011-2022 走看看