LeetCode11:盛最多水的容器
Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of the line i is at (i, ai) and (i, 0). Find two lines, which, together with the x-axis forms a container, such that the container contains the most water.
Notice that you may not slant the container.
用时最快的一个解决方案,出自Python版[leetcode]11. 盛最多水的容器(难度中等)。也有另外两个,思路一样,代码实现略微不同,用时稍慢。Leetcode 11.盛最多水的容器 By Python;leetcode 11. 盛最多水的容器 - 两种解法 - python。
class Solution:
def maxArea(self, height: List[int]) -> int:
i, j, res = 0, len(height) - 1, 0
while i < j:
if height[i] < height[j]:
res = max(res, height[i] * (j - i))
i += 1
else:
res = max(res, height[j] * (j - i))
j -= 1
return res
LeetCode14:最长公共前缀
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string "".
代码出自Leetcode——14.最长公共前缀(python)。这篇文章给出了三种不同的解法,其中下面这个是用时和占存最少的,思路也很清奇。
class Solution:
def longestCommonPrefix(self, strs):
if not strs: return ""
s1 = min(strs)
s2 = max(strs)
for i, x in enumerate(s1):
if x != s2[i]:
return s2[:i]
return s1
LeetCode15:三数之和
Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Notice that the solution set must not contain duplicate triplets.
代码出自team-learning-program/LeetCodeTencent/015 三数之和.md。解决方法的核心思想就是双指针,一个从前向后,一个从后向前。
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
任务链接:
team-learning-program/LeetCodeTencent/011 盛最多水的容器.md
team-learning-program/LeetCodeTencent/014 最长公共前缀.md
team-learning-program/LeetCodeTencent/015 三数之和.md