难度简单393收藏分享切换为英文接收动态反馈
给你两个 没有重复元素 的数组
nums1和nums2,其中nums1是nums2的子集。请你找出
nums1中每个元素在nums2中的下一个比其大的值。
nums1中数字x的下一个更大元素是指x在nums2中对应位置的右边的第一个比x大的元素。如果不存在,对应位置输出-1。
示例 1:
输入: nums1 = [4,1,2], nums2 = [1,3,4,2]. 输出: [-1,3,-1] 解释: 对于 num1 中的数字 4 ,你无法在第二个数组中找到下一个更大的数字,因此输出 -1 。 对于 num1 中的数字 1 ,第二个数组中数字1右边的下一个较大数字是 3 。 对于 num1 中的数字 2 ,第二个数组中没有下一个更大的数字,因此输出 -1 。示例 2:
输入: nums1 = [2,4], nums2 = [1,2,3,4]. 输出: [3,-1] 解释: 对于 num1 中的数字 2 ,第二个数组中的下一个较大数字是 3 。 对于 num1 中的数字 4 ,第二个数组中没有下一个更大的数字,因此输出 -1 。
提示:
1 <= nums1.length <= nums2.length <= 10000 <= nums1[i], nums2[i] <= 104nums1和nums2中所有整数 互不相同nums1中的所有整数同样出现在nums2中
题解1:三个循环 O(N3)
class Solution {
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
int[] res = new int[nums1.length];
for(int i=0;i<nums1.length;i++){ 遍历一遍nums1
res[i]=-1; 全部设置为-1
for(int j=0;j<nums2.length;j++){
if(nums2[j]==nums1[i]){ 在nums2中找到nums1[i]的位置
for(int k=j;k<nums2.length;k++){ 在nums2找到的位置中 后面找到大于nums1的数
if(nums1[i]<nums2[k]){
res[i]=nums2[k];
break; 跳出找大于它的数
}
}
break; 跳出找nums1[i]在其中的位置
}
}
}
return res;
}
}
执行用时:4 ms, 在所有 Java 提交中击败了93.30%的用户
内存消耗:38.7 MB, 在所有 Java 提交中击败了37.67%的用户
题解2:栈 O(MN)
class Solution {
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
int[] res = new int[nums1.length];
Stack<Integer> stack =new Stack<>();
for(int num:nums2){
stack.push(num);
}
for(int i=0;i<nums1.length;i++){
Stack<Integer> temp = new Stack<>();
boolean isFound =false;
int cur = nums1[i];
int max = -1;
while(!stack.isEmpty() && !isFound){
int top =stack.pop();
if(top>cur){
max=top;
}else if(top==cur){
isFound =true;
}
temp.push(top);
}
res[i] = max;
while(!temp.isEmpty()){
stack.push(temp.pop());
}
}
return res;
}
}
题解3:栈+哈希表。 将nums2入栈找每一个数最大的下一个数。记录到hashmap中。
class Solution {
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
int[] res = new int[nums1.length];
Stack<Integer> stack = new Stack<>();
HashMap<Integer,Integer> map = new HashMap<>();
for(int num:nums2){
while(!stack.isEmpty()&&num>stack.peek()){
int temp=stack.pop();
map.put(temp,num);
}
stack.push(num);
}
while(!stack.isEmpty()){
map.put(stack.pop(),-1);
}
for(int i=0 ;i<nums1.length;i++){
res[i]=map.get(nums1[i]);
}
return res;
}
}

695

被折叠的 条评论
为什么被折叠?



