Top 100 Linked Question 修炼------第155题、第160题

本文深入解析了MinStack的设计,一种支持快速查找最小元素的栈结构,以及寻找两个链表相交节点的算法。通过实例说明了如何在O(1)时间复杂度内找到栈中的最小值,以及如何通过调整链表遍历策略来简化相交节点的查找。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

155. Min Stack

题目链接

题目解释:设计一个栈的数据结构,使得这个数据结构能够支持入栈、出栈、取得栈顶元素以及在线性时间内找到最小的元素。

  • push(x) -- 将x元素入栈
  • pop() -- 将栈顶元素从栈中移除
  • top() -- 获取栈顶元素
  • getMin() -- 在栈中找到最小的元素

Example:

MinStack minStack = new MinStack();
minStack.push(-2);
minStack.push(0);
minStack.push(-3);
minStack.getMin();   --> Returns -3.
minStack.pop();
minStack.top();      --> Returns 0.
minStack.getMin();   --> Returns -2.

题目分析:这个题目是很基础的栈栈操作,需要注意的一点就是在常数时间内找到最小值这个操作,为了保持这个操作,我们需要另外维护一个最小值的栈,弹出元素和入栈元素需要处于一一对应的状态:

class MinStack(object):
    def __init__(self):
        self.nums = []
        self.mins = [2 ** 32 - 1]

    def push(self, x):
        self.nums.append(x)
        # min中存的是最小的元素
        self.mins.append(min(self.mins[-1], x))

    def pop(self):
        # 需要进行同步弹出操作
        self.nums.pop()
        self.mins.pop()

    def top(self):
        return self.nums[-1]

    def getMin(self):
        return self.mins[-1]

160. Intersection of Two Linked Lists

题目链接

题目解释:找到两个链表相交的结点。若两个链表不相交,那么返回NULL

Example 1:

Input: intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5], skipA = 2, skipB = 3
Output: Reference of the node with value = 8
Input Explanation: The intersected node's value is 8 (note that this must not be 0 if the two lists intersect). 
From the head of A, it reads as [4,1,8,4,5]. From the head of B, it reads as [5,0,1,8,4,5]. 

There are 2 nodes before the intersected node in A; There are 3 nodes before the intersected node in B.

PS:就给出一个示例了,其他的感觉都差不多了.....

题目分析:这个题目应该是比较常见的题了,就是计算两个链表相交的结点,如上图所示,A链表的长度为5,B链表的长度为6。现在我们假设A,B链表相交,那么一个重要的知识点就是若A,B链表在某个结点相交,那么在相交结点之后,两个链表还是一直相交的。如上图在8处相交,那么他们共同的结点还有8后面的4和5.

弄明白这个问题之后,题目就是变得简单了。因为在相交之后两个链表的长度相等,那么只要让他们的工作指针同时距离最后一个节点的某个位置出发(直接就是较短链表的长度),那么就可以营造一个共同移动的现象,如果两个链表的工作指针重合了,那么就是有公共交点,否则两个链表不相交。

class Solution(object):
    def getIntersectionNode(self, headA, headB):
        """
        :type head1, head1: ListNode
        :rtype: ListNode
        """
        curA,curB = headA,headB
        lenA,lenB = 0,0
        # 分别计算两个链表的长度
        while curA is not None:
            lenA += 1
            curA = curA.next
        while curB is not None:
            lenB += 1
            curB = curB.next
        curA,curB = headA,headB
        # 移动指针,使其最后两个指针能够同时移动
        if lenA > lenB:
            for i in range(lenA-lenB):
                curA = curA.next
        elif lenB > lenA:
            for i in range(lenB-lenA):
                curB = curB.next
        while curB != curA:
            curB = curB.next
            curA = curA.next
        return curA

总结

以前觉得很难的题,现在觉得不堪一击,加油.........

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值