Appearance
0496-下一个更大元素I
https://leetcode.cn/problems/next-greater-element-i
nums1 中数字 x 的 下一个更大元素 是指 x 在 nums2 中对应位置 右侧 的 第一个 比 x 大的元素。
给你两个 没有重复元素 的数组 nums1 和 nums2 ,下标从 0 开始计数,其中nums1 是 nums2 的子集。
对于每个 0 <= i < nums1.length ,找出满足 nums1[i] == nums2[j] 的下标 j ,并且在 nums2 确定 nums2[j] 的 下一个更大元素 。如果不存在下一个更大元素,那么本次查询的答案是 -1 。
返回一个长度为 nums1.length 的数组 ans 作为答案,满足 ans[i] 是如上所述的 下一个更大元素 。
示例 1:
输入:nums1 = [4,1,2], nums2 = [1,3,4,2].
输出:[-1,3,-1]
解释:nums1 中每个值的下一个更大元素如下所述:
4 ,用加粗斜体标识,nums2 = [1,3,4,2]。不存在下一个更大元素,所以答案是 -1 。
1 ,用加粗斜体标识,nums2 = [1,3,4,2]。下一个更大元素是 3 。
2 ,用加粗斜体标识,nums2 = [1,3,4,2]。不存在下一个更大元素,所以答案是 -1 。
示例 2:
输入:nums1 = [2,4], nums2 = [1,2,3,4].
输出:[3,-1]
解释:nums1 中每个值的下一个更大元素如下所述:
2 ,用加粗斜体标识,nums2 = [1,2,3,4]。下一个更大元素是 3 。
4 ,用加粗斜体标识,nums2 = [1,2,3,4]。不存在下一个更大元素,所以答案是 -1 。
提示:
- 1 <= nums1.length <= nums2.length <= 1000
- 0 <= nums1[i], nums2[i] <= 10^4
- nums1和nums2中所有整数 互不相同
- nums1 中的所有整数同样出现在 nums2 中
进阶:你可以设计一个时间复杂度为 O(nums1.length + nums2.length) 的解决方案吗?
思路:暴力法
根据题意,从 nums2 中找出 nums1[i] 的索引值(可以使用hash表加速),然后遍历到 nums2 查看是否有大与 nums1[i] 的数值
参考代码
csharp
public class Solution {
public int[] NextGreaterElement(int[] nums1, int[] nums2) {
//将nums2加入hash表中去,可以快速找到索引
Dictionary<int,int> dict = new Dictionary<int,int>();
for(int i=0; i<nums2.Length; i++){
dict.Add(nums2[i],i);
}
int[] result = new int[nums1.Length];
for(int i=0; i<nums1.Length; i++){
int value = nums1[i];
int index = dict[value];
result[i] = -1;
for(int j=index+1;j<nums2.Length; j++){
if(nums2[j] > nums1[i]){
result[i] = nums2[j];
break;
}
}
}
return result;
}
}
思路:单调栈
将第一个数组加入hash表中去,遍历第二个数组,降序加入栈,当发现有大于栈中元素时,弹出,更新索引值。
参考代码
csharp
public class Solution{
public int[] NextGreaterElement(int[] nums1, int[] nums2){
if(nums1.Length == 0 || nums2.Length == 0){
return new int[]{};
}
int[] result = new int[nums1.Length];
Dictionary<int,int> dict = new Dictionary<int,int>();
for(int i=0; i<nums1.Length; i++){
dict.Add(nums1[i],i);
//设置默认值
result[i] = -1;
}
//初始化为 -1
Stack<int> stack = new Stack<int>();
stack.Push(0);
for(int i=1; i<nums2.Length; i++){
while(stack.Count > 0 && nums2[i] > nums2[stack.Peek()]){
int index = stack.Pop();
if(dict.ContainsKey(nums2[index])){
int num1Index = dict[nums2[index]];
result[num1Index] = nums2[i];
}
}
stack.Push(i);
}
return result;
}
}
复习:20220515
注意点:加入的是key,查询出来的index要转成key
csharp
public class Solution {
public int[] NextGreaterElement(int[] nums1, int[] nums2) {
Dictionary<int,int> dict = new Dictionary<int,int>();
int[] result = new int[nums1.Length];
for(int i=0; i<nums1.Length; i++){
dict.Add(nums1[i],i); //索引加入
result[i] = -1; //设置默认值
}
Stack<int> stack = new Stack<int>();
stack.Push(0);
for(int i=1;i<nums2.Length; i++){
while(stack.Count > 0 && nums2[i] > nums2[stack.Peek()]){
int index = stack.Pop();
int key = nums2[index];
if(dict.ContainsKey(key)){
result[dict[key]] = nums2[i];
}
}
stack.Push(i);
}
return result;
}
}
AlgoPress