-
- 两数相加
-
- 盛最多水的容器
-
- 电话号码的字母组合
-
- 删除链表的倒数第 N 个结点
-
- 下一个排列
2. 两数相加
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
cn = 0 #进位
head = ListNode(0)
p = head
while l1 or l2 or cn:
tmp = (l1.val if l1 else 0) +(l2.val if l2 else 0)+cn
p.val = tmp%10
cn =tmp//10
if l1:
l1 = l1.next
if l2:
l2 = l2.next
if l1 or l2 or cn:
p.next = ListNode(0)
p = p.next
return head
11. 盛最多水的容器
双指针,始终移动高度较小的那一边
class Solution:
def maxArea(self, height: List[int]) -> int:
ans = 0
l,r = 0, len(height)-1
while l <= r:
area = min(height[l],height[r])*(r-l)
ans = max(ans, area)
if height[l] < height[r]:
l += 1
else:
r -= 1
return ans
17. 电话号码的字母组合
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
if len(digits) == 0:
return []
dic = {
'2':['a','b','c'],
'3':['d','e','f'],
'4':['g','h','i'],
'5':['j','k','l'],
'6':['m','n','o'],
'7':['p','q','r','s'],
'8':['t','u','v'],
'9':['w','x','y','z']
}
def backtrace(tmp,digits):
if len(digits) == 0:
res.append(tmp)
return
else:
for letter in dic[digits[0]]:
backtrace(tmp+letter, digits[1:])
res = []
backtrace('',digits)
return res
19. 删除链表的倒数第 N 个结点
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
dummy = ListNode(0,head)
d = dummy # 删除的节点
p = head # 寻找尾部节点
for i in range(n):
p = p.next
while p:
d= d.next
p=p.next
d.next = d.next.next
return dummy.next
31. 下一个排列
class Solution:
def nextPermutation(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
i = len(nums)-2
while i>=0 and nums[i]>=nums[i+1]:
i-=1
if i >=0:
j = len(nums)-1
while j>=0 and nums[j]<=nums[i]:
j-=1
nums[i],nums[j] = nums[j],nums[i]
l,r = i+1,len(nums)-1
while l<r:
nums[l],nums[r] = nums[r],nums[l]
l+=1
r-=1