16、最接近的三数之和
class Solution:
def threeSumClosest(self, nums: List[int], target: int) -> int:
n = len(nums)
nums.sort()
sum_list = []
for i in range(n):
L = i + 1
R = n - 1
while L < R:
sum = nums[i] + nums[L] + nums[R]
sum_list.append(sum)
if sum < target:
L += 1
elif sum > target:
R -= 1
else:
return sum
# print(sum_list)
sum_list.sort()
# print(sum_list)
res = abs(target - sum_list[-1])
res_num = sum_list[-1]
for num in sum_list:
if abs(target - num) < res:
res_num = num
res = abs(target - num)
return res_num
20、有效的括号
class Solution:
def isValid(self, s: str) -> bool:
while '{}' in s or '()' in s or '[]' in s:
s = s.replace('{}', '')
s = s.replace('[]', '')
s = s.replace('()', '')
return s == ''
21、合并两个有序链表
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
res = ListNode(None)
node = res
while l1 and l2:
if l1.val<l2.val:
node.next,l1 = l1,l1.next
else:
node.next,l2 = l2,l2.next
node = node.next
if l1:
node.next = l1
else:
node.next = l2
return res.next