【LeetCode】496. Next Greater Element I

Python版本:3.6.2

496. Next Greater Element I

自己的代码:
class Solution:
    def nextGreaterElement(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        res = []
        for item1 in nums1:
            flag = 0
            if nums2.index(item1)+1 == len(nums2):
                res.append(-1)
            else:
                for i in range(nums2.index(item1) + 1, len(nums2)):
                    if nums2[i] > item1:
                        res.append(nums2[i])
                        flag = 1
                        break
                if not flag:
                    res.append(-1)
        return res
速度:

这题关键点在于理解题目的意思,discussion里有很多表示同感,感觉不理解题目的意思。题目其实是想求出nums1中每个元素对应的在nums2中的位置右边有没有比它大的,有就返回那第一个比他大的,没有就返回-1。如果nums1中对应的是nums2中最有一个数,那么右边没有数了,自然也不存在比他更大的数则返回-1。

欣赏大神的代码,简洁明了:
class Solution:
    def nextGreaterElement(self, findNums, nums):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: List[int]
        """
        def helper(num):
            for tmp in nums[nums.index(num):]:
                if tmp > num:
                    return tmp
            return -1

        return map(helper, findNums)
检验下:
a = Solution()
print(list(a.nextGreaterElement(findNums=[2,4], nums=[1,2,3,4])))
输出:
[3, -1]
map(func, seq1 [, seq2,...])
作用:将func函数作用于seq1中的每一个元素,并得到一个新的seq。函数返回的是一个迭代器,可以以list的形式返回。

  • 只有一个seq时:
print(list(map(lambda x: x % 2, range(7))))
输出:

[0, 1, 0, 1, 0, 1, 0]
  • 有多个seq时:
print(list(map(lambda x, y: x ** y, [1, 2, 3], [1, 2, 3])))
输出:

[1, 4, 27]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值