目录
1.1题目描述
给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。
说明:不允许修改给定的链表。
1.2 思路
首先可以用快慢指针链表是否有环。假设链表头部到环起点的距离为n,环的长度为m,快指针每次走两步,慢指针每次走一步,快慢指针在走了慢指针走t步后相遇,那么相遇的位置是(t - n) % m + n=(2*t - n)%m + n,那么得到t%m = 0,所以头部和相遇的位置一起走n步会重新相遇。那么,头部和相遇点再次走,知道相遇得到的点就为起点。
1.3 代码
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def detectCycle(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head == None or head.next == None:
return None
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
tmp = head
while tmp != fast:
tmp,fast = tmp.next,fast.next
return tmp
return None
2.1 题目 155 Min Stack
题意分析:
实现一个小的栈,包括初始化,push,pop,top,和getMin。
2.2 题目思路
思路是用两个数组来处理。
2.3 代码
class MinStack(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.stack1 = []
self.stack2 = []
def push(self, x):
"""
:type x: int
:rtype: nothing
"""
self.stack1.append(x)
if len(self.stack2) == 0 or x <= self.stack2[-1]:
self.stack2.append(x)
def pop(self):
"""
:rtype: nothing
"""
tmp = self.stack1.pop()
if tmp == self.stack2[-1]:
self.stack2.pop()
def top(self):
"""
:rtype: int
"""
return self.stack1[-1]
def getMin(self):
"""
:rtype: int
"""
return self.stack2[-1]