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     }
复制代码

 

posted @   daniel456  阅读(121)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示