Leetcode 496. 下一个更大元素 I

给你两个 没有重复元素 的数组 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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值