链表中环的入口节点
给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出null。
解法
参考:https://blog.csdn.net/wszll_Alex/article/details/86741909
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def EntryNodeOfLoop(self, pHead):
# write code here
if not pHead:
return None
fast = slow = pHead
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if fast == slow:
fast = pHead
while fast != slow:
fast = fast.next
slow = slow.next
return fast
return None
包含min函数的栈
定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。
注意:保证测试中不会当栈为空的时候,对栈调用pop()或者min()或者top()方法。
解法
其实就是提前存下一个min值,随时更新它就可以。
# -*- coding:utf-8 -*-
class Solution:
def __init__(self):
self.stack = []
self.mi = 100000
def push(self, node):
# write code here
self.stack.append(node)
if node < self.mi:
self.mi = node
def pop(self):
# write code here
t = self.stack[-1]
self.stack = self.stack[:-1]
if t == self.mi:
self.mi = 100000
for x in self.stack:
if x < self.mi:
self.mi = x
return t
def top(self):
# write code here
t = self.stack[-1]
return t
def min(self):
# write code here
return self.mi
字符流中第一个不重复的字符
请实现一个函数用来找出字符流中第一个只出现一次的字符。例如,当从字符流中只读出前两个字符"go"时,第一个只出现一次的字符是"g"。当从该字符流中读出前六个字符“google"时,第一个只出现一次的字符是"l"。
输出描述:
如果当前字符流没有存在出现一次的字符,返回#字符。
解法
想到了哈希,用一个列表存储所有进来的字符,随时判断每个字符是否重复,并且随时更新当前指向第一个不重复字符的指针。
但是后来看了解析,发现并不需要这么复杂,可以使用队列的思想,不需要保存下所有字符,只需要保存那些不重复的字符。
- 入队:获取字符流中的一个字符时,当我们判断它是不重复时,将它加入队列;
- 输出/出队:注意,因为队列中存储的 “不重复字符” 在一系列的流读取操作后,随时有可能改变状态(变重复),所以,队列中的字符不能直接输出,要先进行一次重复判断,如果发现队头字符已经重复了,就将它移出队列并判断新的队头,否则,输出队头的值;
# -*- coding:utf-8 -*-
class Solution:
def __init__(self):
self.s = []
self.dic = {}
self.idx = -1
# 返回对应char
def FirstAppearingOnce(self):
# write code here
if self.idx == -1:
return "#"
return self.s[self.idx]
def Insert(self, char):
# write code here
self.s.append(char)
if char not in self.dic:
self.dic[char] = 1
if self.idx == -1:
self.idx = len(self.s) - 1
else:
self.dic[char] += 1
if self.idx != -1 and self.dic[self.s[self.idx]] > 1:
flag = 0
for i in range(self.idx + 1, len(self.s)):
if self.dic[self.s[i]] == 1:
self.idx = i
flag = 1
break
if flag == 0:
self.idx = -1
把二叉树打印出多行
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
解法
二叉树的层次遍历用的就是BFS,为了确定当前是哪一行,所以需要在队列中再保存一个当前的层数。
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# 返回二维列表[[1,2],[4,5]]
def Print(self, pRoot):
# write code here
if not pRoot:
return []
res = [[]]
q = []
q.append((pRoot, 0))
while q:
cur, n = q.pop(0)
if n >= len(res):
res.append([])
res[n].append(cur.val)
if cur.left:
q.append((cur.left, n + 1))
if cur.right:
q.append((cur.right, n + 1))
return res