码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode刷题记录-20181022

时间:2018-10-22 20:16:22      阅读:152      评论:0      收藏:0      [点我收藏+]

标签: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]= 1
11             else:
12                 dict1[i] +=1
13         for i in dict1:
14             if dict1[i] ==1:
15                 return i
View Code

方法二:使用集合set(),返回集合差

技术分享图片
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)
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 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
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: 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
View Code

 

Leetcode刷题记录-20181022

标签:asc   ict   opened   分享图片   oat   one   pen   type   next   

原文地址:https://www.cnblogs.com/autoyzz/p/9831498.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!