给你两个 没有重复元素 的数组 nums1 和 nums2 ,其中nums1 是 nums2 的子集。
请你找出 nums1 中每个元素在 nums2 中的下一个比其大的值。
nums1 中数字 x 的下一个更大元素是指 x 在 nums2 中对应位置的右边的第一个比 x 大的元素。如果不存在,对应位置输出 -1 。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/next-greater-element-i
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路:这道题可以用两个栈来解决。先把nums2的所有元素放入stack里。然后对nums1进行遍历,对于每一个nums1的元素,创建一个新栈temp,如果stack的顶端元素大于nums1中的元素,那么对max进行更新,如果相等,则停止循环,并把max的值放入结果数组res中。然后继续下一个判断下一个nums1中的元素,直到遍历完成。
Java:
执行用时:155 ms, 在所有 Java 提交中击败了5.01%的用户
内存消耗:39.1 MB, 在所有 Java 提交中击败了5.01%的用户
class Solution {
public int[] nextGreaterElement(int[] nums1, int[] nums2) {
Stack<Integer>stack=new Stack<>();
int[]result=new int[nums1.length];
if(nums2.length==0)
{
return nums2;
}
for(int i=0;i<nums2.length;i++)
{
stack.push(nums2[i]);
}
for(int i=0;i<nums1.length;i++)
{
boolean isFound=false;
Stack<Integer>temp=new Stack<>();
int max=-1;
while((!stack.isEmpty())&&!isFound)
{
int pop=stack.pop();
if(pop==nums1[i])
{
isFound=true;
}
if(pop>nums1[i])
{
max=pop;
}
temp.push(pop);
}
result[i]=max;
while(!temp.isEmpty())
{
stack.push(temp.pop());
}
}
return result;
}
}
Python:
执行用时:712 ms, 在所有 Python3 提交中击败了5.03%的用户
内存消耗:15.2 MB, 在所有 Python3 提交中击败了7.04%的用户
class Solution:
def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
res=[]
stack=[]
if len(nums2)==0 or nums2==None:
return nums1
for num in nums2:
stack.append(num)
for num in nums1:
isFound=False
temp=[]
max=-1
while (len(stack)!=0 and not isFound):
pop=stack.pop()
if pop>num:
max=pop
elif pop==num:
isFound=True
temp.append(pop)
res.append(max)
while len(temp)!=0:
stack.append(temp.pop())
return res