第202题 快乐数
处理循环的操作,set()函数只存不同的数,只要循环就不是快乐数:
class Solution:
def isHappy(self, n: int) -> bool:
n = str(n)
visited = set()
while 1:
n = str(sum(int(i) ** 2 for i in n))
if n == "1":
return True
if n in visited:
return False
visited.add(n)
第203题 移除链表元素
先循环判断链表的头结点是否是val,接下来将不等于val的值链接到headNode头结点:
class Solution:
def removeElements(self, head: ListNode, val: int) -> ListNode:
while head is not None and head.val == val:
head = head.next
if not head:
return None
headNode = head
while head.next is not None:
if head.next.val == val:
head.next = head.next.next
else:
head = head.next
return headNode
https://blog.csdn.net/qiubingcsdn/article/details/82765111
第204题 计数质数
用暴力求解法并不能满足时间复杂度:
class Solution:
def countPrimes(self, n: int) -> int:
if n < 2: return 0
isPrimes = [1]*n
isPrimes[0] = isPrimes[1] = 0
for i in range(2,int(n ** 0.5)+1):
if isPrimes[i] == 1:
isPrimes[i * i: n: i] = [0]*len(isPrimes[i * i: n: i])
return sum(isPrimes)
第205题 同构字符串
首先map()函数是将字符串中字母按顺序记下索引,list()输出索引,当然也可以用[*]对对象解包:
class Solution:
def isIsomorphic(self, s: str, t: str) -> bool:
return [*map(s.index, s)] == [*map(t.index, t)]
第206题 反转链表
迭代方法
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
if head == None:
return head
copy_h = ListNode(-1)
copy_h.next = head
cur = head
nxt = cur.next
while nxt != None:
cur.next = nxt.next
nxt.next = copy_h.next
copy_h.next = nxt
nxt = cur.next
return copy_h.next
递归方法
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
if head == None or head.next == None:
return head
next_node = head.next
res = self.reverseList(next_node)
next_node.next = head
head.next = None
return res
第217题 存在重复元素
set函数只记录不重复数字的索引,map则是字母:
class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
if len(nums) <= 1:
return False
else:
return len(set(nums)) != len(nums)
第二种方法,排序:
class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
if len(nums)<=1:
return False
nums.sort()
for i in range(1,len(nums)):
if nums[i-1] == nums[i]:
return True
return False
第219题 存在重复元素2
只要存在两个相同的数的索引相差k就输出True
class Solution:
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
lookup={}
if len(set(nums)) == len(nums): return False
for i, num in enumerate(nums):
if num in lookup and i - lookup[num] <=k:
return True
lookup[num]=i
return False