#496. Next Greater Element I
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.
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.
class Solution:
def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
# index = [-1] * len(nums1)
# res = [-1] * len(nums1)
# for i in range(len(nums1)):
# for j in range(len(nums2)):
# if nums1[i] == nums2[j]:
# index[i] = j
# print(index)
# for i in range(len(nums1)):
# for j in range(index[i],len(nums2)):
# if nums2[j]>nums1[i]:
# res[i] = nums2[j]
# break
# return res
#这道题的简单之处在于数组中没有重复的元素
res = []
stack = []
dic = dict()
for item in nums2:
while(len(stack)>0 and stack[-1]<item):
dic[stack.pop()] = item
stack.append(item)
for i in range(len(nums1)):
res.append(-1)
if nums1[i] in dic:
res[i] = dic[nums1[i]]
return res
#1019. Next Greater Node In Linked List
#注意链表中的元素有可能有相同的元素值
class Solution:
def nextLargerNodes(self, head: ListNode) -> List[int]:
res = []
#声明一个栈(以列表来代替)
stack = []
p = head
count = 0
while(p):
res.append(0)
while(len(stack)>0 and stack[-1][1] < p.val):
res[stack.pop()[0]] = p.val
stack.append((count,p.val))
p = p.next
count+=1
return res
#类似题目503. Next Greater Element II
Given a circular array (the next element of the last element is the first element of the array), print the Next Greater Number for every element. The Next Greater Number of a number x is the first greater number to its traversing-order next in the array, which means you could search circularly to find its next greater number. If it doesn't exist, output -1 for this number.
Example 1:
Input: [1,2,1]
Output: [2,-1,2]
Explanation: The first 1's next greater number is 2;
The number 2 can't find next greater number;
The second 1's next greater number needs to search circularly, which is also 2.
#这道题主要是一个循环的数组,主要是在循环完一遍之后,再针对栈中剩下的元素,在对原数组进行一次扫描,直到栈为空
class Solution:
def nextGreaterElements(self, nums: List[int]) -> List[int]:
res = []
#声明一个栈(以列表来代替)
stack = []
count = 0
# for count in range(len(nums)):
while(count<len(nums)):
res.append(-1)
while(len(stack)>0 and stack[-1][1] < nums[count]):
res[stack.pop()[0]] = nums[count]
stack.append((count,nums[count]))
count+=1
#此时栈中所剩下的元素就是等待被循环的元素
count = 0
for item in nums:
while(len(stack)>0 and stack[-1][1] < nums[count]):
res[stack.pop()[0]] = nums[count]
count+=1
return res