Can you solve this real interview question? Next Greater Element I - The next greater element of some element x in an array is the first greater element that is to the right of x in the same array. You are given two distinct 0-indexed integer arrays num
下一个更大元素 I[Next Greater Element I][简单]——分析及代码[C++] 一、题目 二、分析及代码 1. 单调栈 + 哈希表 (1)思路 (2)代码 (3)结果 三、其他 一、题目 给你两个 没有重复元素 的数组 nums1 和 nums2 ,其中nums1 是 nums2 的子集。 请你找出 nums1 中每个元素在 nums2 中的下一...
publicint[] nextGreaterElement(int[] nums1,int[] nums2) { Stack<Integer> stack =newStack<>(); HashMap<Integer, Integer> map =newHashMap<>();for(inti=nums2.length -1; i >=0; i--) {while(!stack.isEmpty() && stack.peek() < nums2[i]) { stack.pop(); }if(!stack.isEmpty...
此时我们将 nums2[i] 入栈,保持栈的单调性,并对接下来的 nums2[i + 1], nums2[i + 2]... 执行同样的操作。 下面的动画中给出了一个例子。 Java 实现 public class Solution { public int[] nextGreaterElement(int[] findNums, int[] nums) { Stack < Integer > stack = new Stack < > ()...
待全部装完后,map中的元素对就都是该元素和他右侧第一个较大的元素对了,此时只需要遍历num1,从map中取值即可 我的解法 publicint[] nextGreaterElement(int[] findNums,int[] nums) {int[] result =newint[findNums.length];intn=0;for(inti=0; i < findNums.length; i++) {for(intj=0; j < ...
def nextGreaterElement(self,nums1,nums2): stk=[] #单调栈 hashTable={} #哈希表 for i in range(len(nums2)-1,-1,-1): #反向遍历 print(i) cur=nums2[i] while stk!=[] and stk[-1]<=cur: #关键 stk.pop() if stk: hashTable[cur]=stk[-1] ...
public int[] nextGreaterElement(int[] nums1, int[] nums2) { Map<Integer, Integer> indexs = new HashMap<>(); int[] result = new int[nums1.length]; for (int i = 0; i < nums2.length; i++) indexs.put(nums2[i], i); ...
Output: [-1,3,-1] 先从nums2 的最右边元素2开始判断:栈为空,所以给 2 返回 -1,构成一个键值对放入字典; 把2 压入栈(此时是栈底); 4 过来,和栈顶的2对比,4比2大,则给 4 返回 -1,构成一个新的键值对; 由于4 比栈顶的2 大,则把 2 pop 出栈; ...
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]...
Output: [-1,3,-1] 2、代码实现 public class Solution { public int[] nextGreaterElement(int[] findNums, int[] nums) { if (findNums == null || nums == null) { return null; } int findLength = findNums.length; int numsLength = nums.length; ...