Leetcode 160-相交链表,169-多数元素,206-反转链表
160-相交链表
题目描述
- 编写一个程序,找到两个单链表相交的起始节点。
代码(python)
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> None:
h = set()
temp = headA
while temp is not None:
h.add(temp)
temp = temp.next
temp = headB
while temp is not None:
if temp in h:
return temp
temp = temp.next
return None
169-多数元素
题目描述
- 给定一个大小为 n 的数组,找到其中的多数元素。多数元素是指在数组中出现次数 大于 ⌊ n/2 ⌋ 的元素。
你可以假设数组是非空的,并且给定的数组总是存在多数元素。
代码(python)
class Solution:
def majorityElement(self, nums: List[int]) -> int:
#【不断切分的终止条件】
if not nums: return None
if len(nums) == 1: return nums[0]
#【准备数据,并将大问题拆分为小问题】
left = self.majorityElement(nums[:len(nums)//2])
right = self.majorityElement(nums[len(nums)//2:])
#【处理子问题,得到子结果】
#【对子结果进行合并 得到最终结果】
if left == right:
return left
if nums.count(left) > nums.count(right):
return left
else:
return right
206-反转链表
题目描述
- 反转一个单链表。
代码(python)
#迭代
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
if head is None or head.next is None:
return head
p1 = head
p2 = None
while p1 is not None:
temp = p1.next
p1.next = p2
p2 = p1
p1 = temp
return p2
#递归
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
# 一、
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
def recur(cur,prev):
if cur==None: return prev #终止条件:如果cur为空,则开始回溯返回prev
res=recur(cur.next,cur) #递归函数,往后遍历后继节点
cur.next=prev #修改节点引用指向
return res #返回res节点
return recur(head,None)
# 二、
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
if not head or head.next == None: return head
res = self.reverseList(head.next)
head.next.next = head
head.next = None
return res