zoukankan      html  css  js  c++  java
  • 496. 下一个更大元素 I






    方法一思路:用栈

    将nums2顺序入栈stack[],当栈不空时,取待入栈元素num和栈顶元素top比较,若num>top且top在nums1中,则num即是所找的数。

    class Solution(object):
        def nextGreaterElement(self, nums1, nums2):
            """
            :type nums1: List[int]
            :type nums2: List[int]
            :rtype: List[int]
            """
            # 初始化返回值
            ans = [-1]*len(nums1)
            # 用字典记录下nums1中每个元素的下标
            dict = {}
            for i, num in enumerate(nums1):
                dict[num] = i
            # 模拟栈
            stack = []
            # 遍历nums2
            for num in nums2:
                # 当栈不空,且栈顶元素小于待入栈数字
                while stack and stack[-1] < num:
                    # 取栈顶元素
                    top = stack.pop()
                    # 若栈顶元素在nums1中,则num即为nums2右侧比top大的第一个元素,记录在ans中
                    if top in dict:
                        ans[dict[top]] = num
                # 栈空则将当前数字入栈
                stack.append(num)
            return ans
    

    方法二:

    class Solution(object):
        def nextGreaterElement(self, nums1, nums2):
            """
            :type nums1: List[int]
            :type nums2: List[int]
            :rtype: List[int]
            """
           	ans = []
            for i in range(len(nums1)):
                index = nums2.index(nums1[i])
                temp = nums2[index + 1:]
                # 在nums1右侧是否找到更大元素的标志
                flag = False
                for j in range(len(temp)):
                    if temp[j] > nums1[i]:
                        ans.append(temp[j])
                        # 标志置真
                        flag = True
                        break
                # 没找到则返回-1
                if not flag:
                    ans.append(-1)
            return ans
    

    代码三:

    class Solution(object):
        def nextGreaterElement(self, nums1, nums2):
            """
            :type nums1: List[int]
            :type nums2: List[int]
            :rtype: List[int]
            """
            ans = []
            for i in range(len(nums1)):
                index = nums2.index(nums1[i])
                temp = nums2[index + 1:]
                for j in range(len(temp)):
                    if temp[j] > nums1[i]:
                        ans.append(temp[j])
                        break
                # 没找到则返回-1
                # 原来python里的else还能这么用!!
                else:
                    ans.append(-1)
            return ans
    
  • 相关阅读:
    Docker常用命令操作记录
    第一个netty程序--时间服务
    zookeeper+dubbo配置
    通过IRBuilder新建LLVM IR
    TVM结构介绍
    /lib64/libc.so.6 错误导致的系统崩溃
    php 间歇性报 Segmentation fault
    Dell服务器安装OMSA管理工具
    【Selenium学习笔记】网页截图实践
    局域网内网机器上网实操
  • 原文地址:https://www.cnblogs.com/panweiwei/p/12900208.html
Copyright © 2011-2022 走看看