标签:range class __init__ turn 反转链表 init ntp fast +=
(leetcode 204) 求解质数个数
求解质数,使用筛法;
class Solution(object):
def countPrimes(self, n):
"""
:type n: int
:rtype: int
"""
if n == 0 or n==1 or n==2:
return 0
prime = [True for i in range(n)]
for i in range(2,n):
tmp = i
if prime[tmp]:
j = 2
while tmp*j < n:
prime[tmp*j] = False
j += 1
res = 0
for i in range(2,n):
if prime[i]:
res += 1
return res
(leetcode 206) 反转链表
很简单的一道题,但是总是不能理清next的关系;
为什么 head = head.next 与 p.next = new_head 的顺序 不饿能颠倒?
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
new_head = None
while head:
p = head
head = head.next
p.next = new_head
new_head = p
return new_head
(leetcode 876) 寻找链表的中间节点
快慢指针貌似在链表操作中经常使用;
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def middleNode(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
fast = slow = head
while fast and fast.next:
fast = fast.next.next
slow = slow.next
return slow
(leetcode 234)判断一个链表是否为回文链表
需要熟悉链表的基本操作,本题涉及链表反转和找链表的中间点;
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def isPalindrome(self, head):
"""
:type head: ListNode
:rtype: bool
"""
fast = slow = head
while fast and fast.next:
fast = fast.next.next
slow = slow.next
new_head = None
# while slow:
# p = slow.next
# slow.next = new_head
# new_head = slow
# slow = p
while slow:
p = slow
slow = slow.next
p.next = new_head
new_head = p
while new_head:
# print(new_head.val)
if new_head.val != head.val:
return False
new_head = new_head.next
head = head.next
return True
标签:range class __init__ turn 反转链表 init ntp fast +=
原文地址:https://www.cnblogs.com/curtisxiao/p/10708449.html