写在最前面,编程一直是我的短板,希望在leetcode练习中获得进步!
参考Datawhale组队学习中“LeetCodeTencent”
题目一 11. 盛最多水的容器
给定 n 个非负整数 a1,a2,…,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0)。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。
说明:你不能倾斜容器,且 n 的值至少为 2。
双指针 怎么移动指针
此时我们需要移动一个指针。移动哪一个呢?直觉告诉我们,应该移动对应数字较小的那个指针(即此时的左指针)。这是因为,由于容纳的水量是由
代码
class Solution:
def maxArea(self, height: List[int]) -> int:
l, r = 0, len(height) - 1
ans = 0
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
参考链接
时间复杂度 O(N),双指针遍历一次底边宽度 N 。
空间复杂度 O(1),指针使用常数额外空间。
我的结果
执行用时:84 ms, 在所有 Python3 提交中击败了43.85%的用户
内存消耗:16.2 MB, 在所有 Python3 提交中击败了5.06%的用户
题目二 14. 最长公共前缀
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 “”。
代码
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
if not strs:
return ""
length, count = len(strs[0]), len(strs)
for i in range(length):
c = strs[0][i]
if any(i == len(strs[j]) or strs[j][i] != c for j in range(1, count)):
return strs[0][:i]
return strs[0]
作者LeetCode-Solution链接:
我的结果
执行用时:40 ms
内存消耗:15 MB
题目三 15. 三数之和
给定一个包含n个整数的数组nums,判断nums中是否存在三个元素a,b,c,使得a + b + c = 0?找出所有满足条件且不重复的三元组。
注意:答案中不可以包含重复的三元组。
代码
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
nums = sorted(nums)
result = []
for i in range(0, len(nums) - 2):
# 如果最小的数字大于0, 后面的操作已经没有意义
if nums[i] > 0:
break
# 跳过三元组中第一个元素的重复数据
if i > 0 and nums[i-1] == nums[i]:
continue
# 限制nums[i]是三元组中最小的元素
l = i + 1
r = len(nums) - 1
while l < r:
sum = nums[i] + nums[l] + nums[r]
if sum < 0:
l += 1
elif sum > 0:
r -= 1
else:
result.append([nums[i], nums[l], nums[r]])
# 跳过三元组中第二个元素的重复数据
while l < r and nums[l] == nums[l+1]:
l += 1
# 跳过三元组中第三个元素的重复数据
while l < r and nums[r] == nums[r-1]:
r -= 1
l += 1
r -= 1
return result
我的结果