Leetcode - 496. Next Greater Element I

Example 1:

Input:nums1= [4,1,2],nums2= [1,3,4,2].

Output:[-1,3,-1]

Explanation:For number 4 in the first array, you cannot find the next greater number for it in the second array, so output -1.    For number 1 in the first array, the next greater number for it in the second array is 3.    For number 2 in the first array, there is no next greater number for it in the second array, so output -1.

Example 2:

Input:nums1= [2,4],nums2= [1,2,3,4].

Output:[3,-1]

Explanation:For number 2 in the first array, the next greater number for it in the second array is 3.    For number 4 in the first array, there is no next greater number for it in the second array, so output -1.


question



解法:

小伙伴的思路更加简单,时间复杂度O(n),leetcode上击败98%

思路,还是使用stack,让我们来走一遍例子

dic= {}

s = []

[1,3,4,2]

s = [1] ;; since there is nothing in the stack

[3,4,2]

;;;;;;;;;;;;

dic = {1: 3}

[4,2]

s = [3];; since 1 is smaller than 3, and 3 is the first number that greater than 1, so ,we conclude that 1's next grater is 3

;;;;;;;;;;;;

dic = {1: 3 , 3: 4}

[2]

s = [4] , since 4 is greater than 3 , base on the order we know that 4 has to be the value that next greater than 3, so we pop 3 out and add the ans into dic

;;;;;;;;;;;;;

dic = {1: 3 , 3: 4}

[]

s = [4,2] , since 2 is not greater than 2, so we can not pop, we keep the number in there. and this is the end of the nums

so we know that which number has answer and which one does not 

code:

```

class Solution(object):

def nextGreaterElement(self, findNums, nums):

"""

:type findNums: List[int]

:type nums: List[int]

:rtype: List[int]

"""

dic = {}

s = []

i  = 0

while i != len(nums):

if not s or s[-1] > nums[i]:

s.append(nums[i])

i+=1

else:

dic[s[-1]] = nums[i]

s.pop()

print(dic)

ans = []

for i in findNums:

if i in dic:

ans.append(dic[i])

else:

ans.append(-1)

print(ans)

return ans

```

Leetcode - 496. Next Greater Element I_第1张图片










类似于min stack,可以先做minstack再来做这道题目,很类似

min stack

首先我们要先处理一下 nums,如 [1,2,3,4]

我们将他变成


Leetcode - 496. Next Greater Element I_第2张图片

方法如下

从右到左,因为4是最右位,所有4不存在next greater

push 3 into stack, push的时候问 stack的peek是否大于3,大于说明我们找到了nextgreater for 3

所以将【3,4】push into stack

next

push 2 input stack .............是否大于2.....


于是便得到了一个已经处理好了的答案

接下来只要进行搜索就可以,为了加快速度将stack变成一个hashtabe


最后

for i in findnums:

    从hashtable里面dic.get(i),如果 dic.get(i) > i, return i

    else:

            把 dic.get(i) 当作新的key从新搜索,考虑

             nextGreaterElement([137,59,92,122,52,236],[137,59,92,122,52,236])

             就知道原因了


Leetcode - 496. Next Greater Element I_第3张图片

你可能感兴趣的:(Leetcode - 496. Next Greater Element I)