LeetCode第11题: 盛水最多的容器
- 思路: 容器的容量有两个因素决定: 间距和最小高度可以先保证某个变量为最大值, 寻找另一个变量的更大值, 以此来找到比现有容器更大的值
- 这里保证间距始终为最大值, 如果存在容量更大的容器, 那么一定是在当前容器双指针的里边
class Solution:
def maxArea(self, height: List[int]) -> int:
flag = False
i = start = 0
j = end = len(height) -1
h = min(height[start], height[end])
while i < j:
if height[i] > height[j]:
j -= 1
while height[j] <= height[end] and i < j:
j -= 1
if i >= j:
flag = True
break
else:
i += 1
while height[i] <= height[start] and i < j:
i += 1
if i >= j:
falg = True
break
if (j - i) * min(height[i], height[j]) > (end - start) * h:
start = i
end = j
h = min(height[start], height[end])
if flag:
break
return (end - start) * h
复杂度分析: 由于需要遍历一遍列表, 所以设列表长度为n, 复杂度为O(n)
LeetCode第14题: 最长公共前缀
- 依次比较即可
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
if len(strs) < 1:
return ''
i = 0
while i < len(min(strs)):
ch = strs[0][i]
for j in range(1, len(strs)):
if ch != strs[j][i]:
return '' if i == 0 else strs[0][0:i]
i += 1
return strs[0][0:i]
复杂度分析: 假设列表长度为n, 最小字符为m, 如果不匹配, 那么复杂度O(n), 如果匹配最长字符复杂度O(n * m)
LeetCode第15题: 三数之和
- 使用双指针法, 注意防止出现重复
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
nums.sort()
i = 0
j = i + 1
t = len(nums)
k = t - 1
l = []
while i < t - 2:
while j < k:
if -nums[i] == (nums[j] + nums[k]):
l.append([nums[i],nums[j],nums[k]])
j += 1
k -= 1
while j < k and nums[j] == nums[j - 1]:
j += 1
while j < k and nums[k] == nums[k + 1]:
k -= 1
elif -nums[i] >= (nums[j] + nums[k]):
j += 1
else:
k -= 1
i += 1
while i < t - 2 and nums[i] == nums[i - 1]:
i += 1
if nums[i] > 0:
return l
j = i + 1
k = t - 1
return l
复杂度分析: 假设数组长n, 最后情况O(n), 最坏情况: O(n ^ 2)