標籤:asc ict opened 分享圖片 oat one pen type next
136. Single Number
方法一:建立字典,依次迴圈;
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]= 111 else:12 dict1[i] +=113 for i in dict1:14 if dict1[i] ==1:15 return iView Code
方法二:使用集合set(),返回集合差
1 class Solution:2 def singleNumber(self, nums):3 """4 :type nums: List[int]5 :rtype: int6 """7 8 return 2*sum(set(nums))-sum(nums)
View Code
141. Linked List Cycle
判斷是否鏈表中是否有環
思想:設定快慢指標,如快指標為Null 或者快指標.next 為null,那麼沒有環;
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 False10 fast = head.next11 slow = head12 while (slow != fast):13 if fast == None or fast.next == None:14 return False15 fast = fast.next.next16 slow = slow.next17 18 return True
View Code
155. Min Stack
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: int14 :rtype: void15 """16 self.stack.append(x)17 self.min = min(self.min, x)18 19 def pop(self):20 """21 :rtype: void22 """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: int31 """32 return self.stack[-1]33 34 def getMin(self):35 """36 :rtype: int37 """38 return self.min
View Code
Leetcode刷題記錄-20181022