下一个更大的元素

题目描述如下:

 

举个栗子:

 

第一个思路:(简单粗暴)

遍历nums1,对于nums1中的每个元素,在nums2中找到对应位置,接着用while循环找到下一个最大值。复杂度为O(N2)。

 1 class Solution(object):
 2     def nextGreaterElement(self, nums1, nums2):
 3         """
 4         :type nums1: List[int]
 5         :type nums2: List[int]
 6         :rtype: List[int]
 7         """
 8         result = []
 9         for item in nums1:
10             isok = True
11             begin = nums2.index(item)
12             while begin < len(nums2) and isok:
13                 if nums2[begin] > item:
14                     isok = False
15                     result.append(nums2[begin])
16                 begin += 1
17             if isok == True:
18                 result.append(-1)
19         return result

第二个思路

能否进一步优化时间复杂度?

创建一个字典,该字典中的键为nums2中的每个元素,值为当前元素对应的下一个最大值。

寻找每个元素下一个最大值时,假如第一个元素是比较大的数,它可能是一直不用派上用场;假如第一个元素是比较小的数,它很快就能找到下一个最大的数。

由于这种反转性质,必然想要要用栈的数据结构。

 1 class Solution(object):
 2     def nextGreaterElement(self, nums1, nums2):
 3         """
 4         :type nums1: List[int]
 5         :type nums2: List[int]
 6         :rtype: List[int]
 7         """
 8         stack = []
 9         dictnums2 = {j:-1 for j in nums1}
10         for item in nums2:
11             while stack and item > stack[-1]:
12                 dictnums2[stack.pop()] = item
13             stack.append(item)
14         return [dictnums2[i] for i in nums1]

两种思路的执行结果:

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

posted @ 2020-08-06 11:26  张书架  阅读(74)  评论(0)    收藏  举报