16 最接近的三数之和
class Solution:
def threeSumClosest(self, nums: List[int], target: int) -> int:
n = len(nums)
if n < 3:
return 0
nums = sorted(nums)
res = 0
diff = float(inf)
for i in range(n-2):
L = i+1
R = n-1
while L < R:
temp_sum = nums[i] + nums[L] + nums[R]
if abs(temp_sum - target) < diff:
diff = abs(temp_sum - target)
res = temp_sum
if temp_sum == target:
return temp_sum
elif temp_sum -target > 0:
R -= 1
else:
L += 1
return res
20 有效的括号
利用栈,遇到左括号则进栈,遇到右括号则出栈
比较出栈的元素是否和此时的右括号匹配,不匹配则返回False
若遇到右括号,而此时的栈为空,则说明没有与该右括号匹配的左括号,直接返回False
完全匹配的栈应为空
class Solution:
def isValid(self, s: str) -> bool:
n = len(s)
stack = []
for i in range(n):
if s[i] in "({[":
stack.append(s[i])
else:
if stack:
pop = stack.pop()
if pop not in "({[":
return False
if (s[i] == ")" and pop == "(" ) or (s[i] == "]" and pop == "[" ) or (s[i] == "}" and pop == "{" ):
continue
else:
return False
else:
return False
if not stack:
return True
else:
return False
class Solution:
def isValid(self, s: str) -> bool:
stack = ["?"]
dic = {"(":")", "[":"]", "{":"}","?":"?"}
for ch in s:
if ch in dic: stack.append(ch)
else:
if dic[stack.pop()] != ch: return False
return len(stack) == 1
21 合并两个有序链表
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
# 迭代
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode):
head1 = l1
head2 = l2
res_node = ListNode()
head = res_node
# print(head.val)
while head1 and head2:
# print(head.val)
if head1.val <= head2.val:
head.next = head1
head1 = head1.next
else:
head.next = head2
head2 = head2.next
head = head.next
if not head1 and head2:
while head2:
head.next = head2
head = head.next
head2 = head2.next
if not head2 and head1:
while head1:
head.next = head1
head = head.next
head1 = head1.next
return res_node.next
# 递归
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode):
if not l1: return l2
if not l2: return l1
if l1.val <= l2.val:
l1.next = self.mergeTwoLists(l1.next, l2)
return l1
else:
l2.next = self.mergeTwoLists(l2.next,l1)
return l2