Leetcode刷题记录_20181026

202. Happy Number 

最终平方和为1则为快乐肥宅数!循环过程中可建立一个数组,存储中间结果。

 1 class Solution(object):
 2     def isHappy(self, n):
 3         """
 4         :type n: int
 5         :rtype: bool
 6         """
 7         result = 0 
 8         list1 = []
 9         while n > 0:
10             result += (n%10)**2
11             n = n/10
12             if n <= 0:
13                 if result ==1:
14                     return True
15                 else:
16                     if result in list1:
17                         return False
18                     else:
19                         list1.append(result)
20                         n = result
21                         result = 0
View Code

203.Remove Linked List Elements  

删除链表中值为给定数字的节点,返回修改后节点。

 1 # Definition for singly-linked list.
 2 # class ListNode(object):
 3 #     def __init__(self, x):
 4 #         self.val = x
 5 #         self.next = None
 6 
 7 class Solution(object):
 8     def removeElements(self, head, val):
 9         """
10         :type head: ListNode
11         :type val: int
12         :rtype: ListNode
13         """
14         if not head:
15             return None
16         p = head
17         q = head.next
18         while q:
19             if q.val == val:
20                 p.next = q.next
21                 q = q.next
22             else:
23                 p = q
24                 q = q.next
25         if head.val == val:
26             return head.next
27         else:
28             return head
View Code

204. Count Primes

返回n范围内的质数个数。

埃拉托斯特尼筛法

 1 class Solution(object):
 2     def countPrimes(self, n):
 3         """
 4         :type n: int
 5         :rtype: int
 6         """
 7         if n <3:
 8             return 0
 9         result = [True] * n
10         result[0]=result[1] = False
11         for i in range(2,int(n**0.5)+1):
12             if result[i]:
13                 result[i*i:n:i] = [False] * len(result[i*i:n:i])
14         return sum(result)
View Code

 

posted @ 2018-10-26 19:47  adminyzz  阅读(127)  评论(0编辑  收藏  举报