0
点赞
收藏
分享

微信扫一扫

[Leetcode] 每日两题 1019 1791 -day92

Jonescy 2022-02-19 阅读 26

1019. 链表中的下一个更大节点

在这里插入图片描述

单调栈

正常应该是从后向前访问链表 所以这里可以选择反转链表或者将链表转换为数组然后按照索引访问

构建索引的单调栈

遍历整个链表 ,若栈为空或者栈顶索引对应的值大于当前结点值(递减栈) 则入栈

否则对栈顶索引位置进行赋值(当前节点值)

class Solution:
    def nextLargerNodes(self, head: Optional[ListNode]) -> List[int]:
        
        lis = []
        while head != None:
            lis.append(head.val)
            head = head.next
        st = []
        res = [0] * len(lis)
        for i in range(len(lis)):
            while len(st) != 0 and lis[st[- 1]] < lis[i]:
                res[st[- 1]] = lis[i]
                st.pop()
            st.append(i)
            #print(st)
        return res 


1791. 找出星型图的中心节点

在这里插入图片描述

找重复元素 两个边判断就行

class Solution:
    def findCenter(self, edges: List[List[int]]) -> int:
        a,b =0,0
        for i,j in  edges:
            if i == a or i ==b:
                return i
            if j == a or j ==b:
                return j
            a,b= i,j
举报

相关推荐

0 条评论