python--leetcode496. Next Greater Element I

本文探讨了如何在两个数组中寻找特定元素的下一个更大值。通过给出两种算法实现方式,包括一个简单但效率较低的方法和一个高效的O(n)算法,帮助读者理解解决这类问题的基本思路。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

You are given two arrays (without duplicates) nums1 and nums2 where nums1’s elements are subset of nums2. Find all the next greater numbers for nums1's elements in the corresponding places of nums2.

The Next Greater Number of a number x in nums1 is the first greater number to its right in nums2. If it does not exist, output -1 for this number.

Example 1:

Input: nums1 = [4,1,2], nums2 = [1,3,4,2].
Output: [-1,3,-1]
Explanation:
    For number 4 in the first array, you cannot find the next greater number for it in the second array, so output -1.
    For number 1 in the first array, the next greater number for it in the second array is 3.
    For number 2 in the first array, there is no next greater number for it in the second array, so output -1.

Example 2:

Input: nums1 = [2,4], nums2 = [1,2,3,4].
Output: [3,-1]
Explanation:
    For number 2 in the first array, the next greater number for it in the second array is 3.
    For number 4 in the first array, there is no next greater number for it in the second array, so output -1.

Note:

  1. All elements in nums1 and nums2 are unique.

  1. The length of both nums1 and nums2 would not exceed 1000.
这一题的意思就是给两个数组,第一个数组是第二个数组的子数组。找到第一个数组中数字在第二个数组中下一个比它大的元素,如果没有返回-1.
思路如下,无非就是遍历,判断逻辑:
class Solution(object):
    def nextGreaterElement(self, findNums, nums):
        """
        :type findNums: List[int]
        :type nums: List[int]
        :rtype: List[int]
        """
        res=[]
        for i in range(len(findNums)):
            flag=1
            max1=-9999
            for j in range(len(nums)):
                if findNums[i]==nums[j]:
                    for k in range(j,len(nums)):
                        if nums[k]>nums[j]:
                            max1=nums[k]
                            break
                    break
            if max1<findNums[i]:flag=0
            if flag==1:res.append(max1)
            else :res.append(-1)
        return res


s=Solution()
print(s.nextGreaterElement([4,2,3],[1,2,3,4]))
三重循环,其实是比较费时间的。
介绍一种O(n)算法:
   d = {}
        st = []
        ans = []
        
        for x in nums:
            while len(st) and st[-1] < x:
                d[st.pop()] = x
            st.append(x)

        for x in findNums:
            ans.append(d.get(x, -1))
            
        return ans


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

哎呦不错的温jay

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值