1 """ 2 We are given a linked list with head as the first node. Let‘s number the nodes in the list: node_1, node_2, node_3, ... etc. 3 4 Each node may have a next larger value: for node_i, next_larger(node_i) is the node_j.val such that j > i, node_j.val > node_i.val, and j is the smallest possible choice. If such a j does not exist, the next larger value is 0. 5 6 Return an array of integers answer, where answer[i] = next_larger(node_{i+1}). 7 8 Note that in the example inputs (not outputs) below, arrays such as [2,1,5] represent the serialization of a linked list with a head node value of 2, second node value of 1, and third node value of 5. 9 10 11 12 Example 1: 13 14 Input: [2,1,5] 15 Output: [5,5,0] 16 17 Example 2: 18 19 Input: [2,7,4,3,5] 20 Output: [7,0,5,5,0] 21 22 Example 3: 23 24 Input: [1,7,5,1,9,2,5,1] 25 Output: [7,9,9,9,0,5,0,0] 26 27 """ 28 class ListNode: 29 def __init__(self, x): 30 self.val = x 31 self.next = None 32 class Solution1(object): 33 def nextLargerNodes(self, head): 34 if not head.next: 35 return head if head.val != 0 else None #判断头节点是为否为空 36 nums = [] 37 p = head 38 while(p): #将链表转为数组 39 nums.append(p.val) 40 p = p.next 41 stack = [] #创建一个栈 42 res = [0] * len(nums) #保存结果的数组 43 #bug 0 没有加[0] 44 for i, n in enumerate(nums): # 45 while stack and nums[stack[-1]] < n: #!!!单调递减的栈,栈中存的是索引 46 res[stack.pop()] = n 47 stack.append(i) #将索引压栈 48 return res 49 """ 50 runtime error 51 单调递减(增)栈,是一个非常普遍的解法 52 传送门https://blog.csdn.net/qq_17550379/article/details/86519771 53 """ 54 55 """ 56 我们也可以不将链表中的元素存放到一个list里面, 57 而是直接去处理链表,不过对于链表我们无法快速索引具体位置的值, 58 所以我们可以在stack中记录(index, val)数据对。 59 """ 60 class Solution2(object): 61 def nextLargerNodes(self, head): 62 res, stack = list(), list() 63 while head: 64 while stack and stack[-1][1] < head.val: 65 res[stack.pop()[0]] = head.val 66 stack.append([len(res), head.val]) 67 res.append(0) 68 head = head.next 69 return res
原文地址:https://www.cnblogs.com/yawenw/p/12250489.html
时间: 2024-10-02 05:03:12