栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

下一个更大元素I-栈496-python

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

下一个更大元素I-栈496-python

没看答案,暴力解法,时间复杂度O(n^2)。

class Solution:
    def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
        res = []
        
        for i in nums1:
            pos = nums2.index(i)
            for num in nums2[pos:]:
                if num > i:
                    res.append(num)
                    break
            else:
                res.append(-1)
        
        return res

单调栈解法,时间复杂度O(n)。

class Solution:
    def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:      
        stack = []
        m, n = len(nums1), len(nums2)
        pos = {}
        res = [0] * m

        for idx, num in enumerate(nums1):
            pos[num] = idx

        for i in range(n-1, -1, -1):
            while stack and stack[-1] <= nums2[i]:
                stack.pop()

            if nums2[i] in pos.keys():
                if not stack:
                    res[pos[nums2[i]]] = -1
                else:
                    res[pos[nums2[i]]] = stack[-1]
            stack.append(nums2[i])
        
        return res
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/846326.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号