Leetcode刷题记录-20181022
136. Single Number
方法一:建立字典,依次循环;
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 class Solution: 2 def singleNumber(self, nums): 3 """ 4 :type nums: List[int] 5 :rtype: int 6 """ 7 dict1 = {} 8 for i in nums: 9 if i not in dict1: 10 dict1[i]= 1 11 else: 12 dict1[i] +=1 13 for i in dict1: 14 if dict1[i] ==1: 15 return i
方法二:使用集合set(),返回集合差
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 class Solution: 2 def singleNumber(self, nums): 3 """ 4 :type nums: List[int] 5 :rtype: int 6 """ 7 8 return 2*sum(set(nums))-sum(nums)
141. Linked List Cycle
判断是否链表中是否有环
思想:设定快慢指针,如快指针为Null 或者快指针.next 为null,那么没有环;
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 class Solution(object): 2 def hasCycle(self, head): 3 """ 4 :type head: ListNode 5 :rtype: bool 6 """ 7 8 if not head: 9 return False 10 fast = head.next 11 slow = head 12 while (slow != fast): 13 if fast == None or fast.next == None: 14 return False 15 fast = fast.next.next 16 slow = slow.next 17 18 return True
155. Min Stack
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 class MinStack: 2 3 def __init__(self): 4 """ 5 initialize your data structure here. 6 """ 7 self.stack = [] 8 self.min = float('inf') 9 10 11 def push(self, x): 12 """ 13 :type x: int 14 :rtype: void 15 """ 16 self.stack.append(x) 17 self.min = min(self.min, x) 18 19 def pop(self): 20 """ 21 :rtype: void 22 """ 23 if self.stack.pop() == self.min : 24 self.min = min(self.stack) if self.stack else float('inf') 25 26 27 28 def top(self): 29 """ 30 :rtype: int 31 """ 32 return self.stack[-1] 33 34 def getMin(self): 35 """ 36 :rtype: int 37 """ 38 return self.min