第16题
题目
给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,使得它们的和与 target 最接近。返回这三个数的和。假定每组输入只存在唯一答案。
输入:nums = [-1,2,1,-4], target = 1
输出:2
解释:与 target 最接近的和是 2 (-1 + 2 + 1 = 2) 。
思路
在前面用双指针算三数之和等于0的基础上改动哦即可。
class Solution:
def threeSumClosest(self, nums: List[int], target: int) -> int:
if len(nums) < 3:
return 0
nums.sort()
res, cur, n = 0, 0, len(nums)
for i in range(n):
left, right = i+1, n-1
while left < right:
sum1 = nums[i] + nums[left] +nums[right]
if cur == 0: # 主要要想到这步骤的转化
cur = abs(sum1-target)
res = sum1
if abs(sum1-target) < cur:
cur = abs(sum1-target)
res = sum1
if sum1 == target:
return target
elif sum1 > target:
right -= 1
else:
left += 1
return res
第20题
题目
给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串,判断字符串是否有效。
有效字符串需满足:
- 左括号必须用相同类型的右括号闭合。
- 左括号必须以正确的顺序闭合。
输入: "()"
输出: true
输入: "()[]{}"
输出: true
思路
栈的思路即可
class Solution:
def isValid(self, s: str) -> bool:
import collections
d = collections.deque() # 栈
left = ['(','{','[']
flag = True
for x in s:
if x in left:
d.append(x)
else:
if len(d) == 0:
return False
cur = d.pop()
if x == ')' and cur=="(":
continue
elif x=='}' and cur=="{":
continue
elif x==']' and cur=='[':
continue
else:
return False
if len(d) > 0:
return False
return True
第21题
题目
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
输入:l1 = [1,2,4], l2 = [1,3,4]
输出:[1,1,2,3,4,4]
输入:l1 = [], l2 = []
输出:[]
思路
就是python链表的处理要熟悉
# 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:
head = ListNode()
cur = head
while l1 and l2:
if l1.val <= l2.val:
cur.next = l1
cur = l1
l1 = l1.next
else:
cur.next = l2
cur = l2
l2 = l2.next
if l1:
cur.next = l1
else:
cur.next = l2
return head.next