160 相交链表
双指针法
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
pA = headA
pB = headB
while headA != headB:
if headA:
headA = headA.next
else:
headA = pB
if headB:
headB = headB.next
else:
headB = pA
# print(headA.val)
# print(headB.val)
return headA
169 多数元素
# 哈希法
class Solution:
def majorityElement(self, nums: List[int]) -> int:
nums_dict = {}
n = len(nums)
for i in range(n):
if nums[i] in nums_dict:
nums_dict[nums[i]] += 1
else:
nums_dict[nums[i]] = 1
for num in nums_dict:
if nums_dict[num] > n/2: return num
# 摩尔投票法
# 每个不同的数两两抵消,多数的数最后至少还剩下一个
# 初始candidate = nums[0], count = 1, 如果遇到相同的数,则count+1 ,遇到不同的数count - 1, 如果count = 0时,更换候选人
class Solution:
def majorityElement(self, nums: List[int]) -> int:
n = len(nums)
candidate = nums[0]
count = 1
for i in range(1,n):
if nums[i] == candidate: count += 1
else: count -= 1
if count == 0:
candidate = nums[i]
count = 1
return candidate
206 反转链表
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
# 迭代
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
pre = head
cur = None
while pre:
node = pre.next
pre.next = cur
cur = pre
pre = node.next
return cur
# 递归
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
if not head or not head.next: return head
res = self.reverseList(head.next)
head.next.next = head
head.next = None
return res