“这些事儿在熟练之后,也许就像喝口水一样平淡,但却能给初学者带来巨大的快乐,我一直觉得,能否始终保持如初学者般的热情、专注,决定了在做某件事时能走多远,能做多好。” 该系列文章由python编写,遵循LeetBook 列表/腾讯的刷题顺序,所有代码已通过。每日3道,随缘剖析,希望风雨无阻,作为勉励自己坚持刷题的记录。
16. 最接近的三数之和- 双指针,注意和上一题对比【第一遍未写出】:
class Solution:
def threeSumClosest(self, nums: List[int], target: int) -> int:
nums.sort()
n, mindes, res = len(nums), 2**31, []
for first in range(n):
if first>0 and nums[first]==nums[first-1]:
continue
L, R = first+1, n-1
# L和R不能取同一个数,但可以取同一个值
while L 0: R -= 1
else: L += 1
return res
20. 有效的括号
- 栈的方法:
class Solution:
def isValid(self, s: str) -> bool:
stack = []
chardic = {"(":")","{":"}","[":"]"}
for ch in s:
if ch in chardic:
stack.append(ch)
else:
match = stack.pop() if stack else ""
if not match or ch!=chardic[match]: return False
return not stack
26. 删除有序数组中的重复项
- 数组修改使用快慢指针:
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
slow = 0
for fast in range(0, len(nums)):
if fast==slow or nums[fast]==nums[slow]:
continue
else:
slow+=1
nums[slow]=nums[fast]
return slow+1



