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