funcclimbStairs(n int)int{// 1. 斐波那契 递归if n <3{return n
}returnclimbStairs(n-1)+climbStairs(n-2)}
classSolution:defclimbStairs(self, n:int)->int:# 1. 斐波那契数列,递推if n <=0:return0
res, last =1,1for _ inrange(1, n):
res, last = res + last, res
return res
# 2. 斐波那契公式
sqrt_5 = math.sqrt(5)
fib_n = math.pow((1+sqrt_5)/2, n+1)- math.pow((1-sqrt_5)/2, n+1)returnint(fib_n/sqrt_5)
classSolution:defthreeSum(self, nums: List[int])-> List[List[int]]:
nums.sort()
res =[]for i inrange(len(nums)):if i >0and nums[i]== nums[i -1]:continue
l, r = i +1,len(nums)-1while l < r:
ans = nums[i]+ nums[l]+ nums[r]if ans <0:
l +=1elif ans >0:
r -=1else:
res.append([nums[i], nums[l], nums[r]])# breakwhile l < r and nums[l]== nums[l +1]:
l +=1while l < r and nums[r]== nums[r -1]:
r -=1
l +=1
r -=1return res
classSolution:defreverseList(self, head: ListNode)-> ListNode:# 1. 指针法# 申请两个节点,pre和 cur,pre指向None
pre =None
cur = head
while cur:# 记录当前节点的下一个节点
tmp = cur.next# 然后将当前节点指向pre
cur.next= pre
# pre和cur节点都前进一位
pre, cur = cur, tmp
return pre
# 2. 递归解法# 2.1 终止条件是当前节点或者下一个节点 == null# 2.2 在函数内部,改变节点的指向,也就是head的下一个节点指向head递归函数那句# 递归终止条件是当前为空,或者下一个节点为空if head isNoneor head.nextisNone:return head
# 这里的cur就是最后一个节点
cur = self.reverseList(head.next)
head.next.next= head
# 防止链表循环,需要将head.next设置为空
head.next=None# 每层递归函数都返回cur,也就是最后一个节点return cur
# Definition for singly-linked list.# class ListNode:# def __init__(self, x):# self.val = x# self.next = NoneclassSolution:defswapPairs(self, head: ListNode)-> ListNode:# 递归方法# 结束条件:ifnot head ornot head.next:return head
pre_point = head
after_point = head.next# 交换两节点
pre_point.next= self.swapPairs(after_point.next)
after_point.next= pre_point
return after_point
classSolution:defswapPairs(self, head: ListNode)-> ListNode:# 方法二:
thead = ListNode(-1)
thead.next= head
c = thead
while c.nextand c.next.next:
a, b = c.next, c.next.next
c.next, a.next= b, b.next
b.next= a
c = c.next.nextreturn thead.next
classSolution:defhasCycle(self, head: ListNode)->bool:# 方法1: 哈希表# 从头遍历链表,将遍历到的元素放入字典里,如果有环的情况下那么必然会重复出现在哈希表;如果没有环,那么指针移动到最后就退出
dic ={}while head:if head in dic:returnTrueelse:
dic[head]=1
head = head.nextreturnFalse# 方法2: 快慢指针追该碰撞ifnot head:returnFalse
slow = head
quick = head
while quick and slow:
slow = slow.nextif quick.next:# quick跳两次,所以要判断quick.next是否为空
quick = quick.next.nextelse:returnFalseif quick is slow:returnTruereturnFalse
classSolution:defdetectCycle(self, head: ListNode)-> ListNode:# 方法1: 哈希表
visited =set()
node = head
while node:if node in visited:return node
else:
visited.add(node)
node = node.nextreturnNone# 方法2: Floyd算法(双指针两次相遇)
fast, slow = head, head
whileTrue:ifnot(fast and fast.next):return
fast, slow = fast.next.next, slow.nextif fast == slow:break
fast = head
while fast != slow:
fast, slow = fast.next, slow.nextreturn fast