题意:给你两个数组nums1和nums2,并且nums1的元素是nums2的子集(说白了nums1是nums2的子集)。找到所有nums1的元素可以对应在nums2的对应位置上的next greater numbers。
这个The Next Greater Number的定义是在nums2中对应的nums1的元素往后看,第一个比这个元素大的数,如果这个数不存在,那就输出-1。
注:
nums1和nums2的所有元素都是唯一的。nums1和nums2的长度不会超过10000。
解:这道题很简单,唯一需要注意的就是每次都是从nums1的元素在nums2的位置上开始遍历nums2来寻找对应的元素,而且只要第一个比它大的元素。
直接上代码:
def test(self, findNums, nums):
num = []
for x in findNums:
flag = False
for n in nums[nums.index(x) : len(nums)]:
if n > x:
num.append(n)
flag = True
break
if not flag:
num.append(-1)
return num
代码没啥好说的,就是基本思路。
上大神解决方案:
class Solution(object):
def nextGreaterElement(self, findNums, nums):
"""
:type findNums: List[int]
:type nums: List[int]
:rtype: List[int]
"""
return [next((n for n in nums[nums.index(x):] if n > x), -1) for x in findNums]
每次看到大神的代码都觉得自己果然还是太渣了。
首先一点关于list的切片,既然要切到最后一位,完全没必要写len(nums),其次就是对于next()函数的运用了,这里真的是佩服大神的思维能力,竟然能想到用next()函数来解决问题。关于next()函数,传入一个迭代器,每次会返回一个迭代器的序列值,迭代器的值全部返回后,会返回一个异常StopIteration,这时候可以设置第二个参数,作为迭代器结束后的默认返回值。
以上。
5459




被折叠的 条评论
为什么被折叠?



