LeetCode 496 Next Greater Element I 解题报告

题目要求

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.

题目分析及思路

给定两个数组nums1和nums2,且nums1是nums2的子集,要求找到nums1中的所有元素在nums2中对应的the next greater numbers。nums1中的元素的the next greater number是该元素在nums2的位置右起第一个比自身大的元素。如果不存在,就返回-1。可以使用列表推导式,并定义一个函数,该函数的作用是得到元素的the next greater number,具体实现是获得元素在nums2中的索引,并遍历nums2,若有元素同时满足索引和值都比已知元素的大,则获取该元素,跳出循环。

python代码

class Solution:

    def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:

        def great_num(i):

            great_list = []

            idx = nums2.index(i)

            for j,val in enumerate(nums2):

                if j > idx and val > i:

                    great_list.append(val)

                    break

            if len(great_list) == 0:

                return -1

            else:

                return great_list[0]

        return [great_num(i) for i in nums1]

            

        

 

转载于:https://www.cnblogs.com/yao1996/p/10469095.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值