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
此时我们将 nums2[i] 入栈,保持栈的单调性,并对接下来的 nums2[i + 1], nums2[i + 2]... 执行同样的操作。 下面的动画中给出了一个例子。 Java 实现 public class Solution { public int[] nextGreaterElement(int[] findNums, int[] nums) { Stack < Integer > stack = new Stack < > ()...
使用两层循环,先找到nums1的元素在nums2中的对应元素,然后从nums2中找到的元素的下一位往右开始判断,找到比当前元素大的元素,找得到就将其作为结果数组的元素添加进去,否则就将-1添加进结果数组。 publicint[]nextGreaterElement(int[] nums1,int[] nums2){int[] result =newint[nums1.length];for(inti=0;...
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...
class Solution1 { public: vector<int> nextGreaterElement(vector<int>& findNums, vector<int>& nums) { int findNumsSize=findNums.size(); int numsSize=nums.size(); vector<int> ret(findNumsSize); for(int i=0; i<findNumsSize; ++i){ ...
下一个更大元素 I[Next Greater Element I][简单]——分析及代码[C++] 一、题目 二、分析及代码 1. 单调栈 + 哈希表 (1)思路 (2)代码 (3)结果 三、其他 一、题目 给你两个 没有重复元素 的数组 nums1 和 nums2 ,其中nums1 是 nums2 的子集。 请你找出 nums1 中每个元素在 nums2 中的下一...
Output: [-1,3,-1] 先从nums2 的最右边元素2开始判断:栈为空,所以给 2 返回 -1,构成一个键值对放入字典; 把2 压入栈(此时是栈底); 4 过来,和栈顶的2对比,4比2大,则给 4 返回 -1,构成一个新的键值对; 由于4 比栈顶的2 大,则把 2 pop 出栈; ...
Leetcode496. Next Greater Element I 这个题,开始我是想用find和upper_bound两个函数解决,但是 upper_bound并不对。 upper_bound返回的是插入的数字的上界。 如一个数组number序列1,2,2,4.upper_bound(2)后,返回的位置是3(下标)也就是4所在的位置。
Next Greater Element I? Leetcode 496. Next Greater Element I的时间复杂度是多少? 1. Description 2. Solution **解析:**Version 1,由于元素是唯一的,通过循环找出每个nums2中的满足条件结果保存到字典中,遍历nums1,获得结果。Version 2通过使用栈来寻找满足条件的结果,减少搜索时间。 Version 1 代码语言:...
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; ...