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]