暴力解法超时,使用双指针:
- 初始时指针left指向最左边,指针right指向最右边;
- 当left小于right时:
- 计算指针left到指针right之中盛多少水,更新res;
- 比较指针left和指针right指向的元素哪个小,移动小的那个指针;
class Solution(object):
def maxArea(self, height):
left,right=0,len(height)-1
res=0
while left<right:
if height[left]<=height[right]:
res=max(res,(right-left)*height[left])
left+=1
else:
res=max(res,(right-left)*height[right])
right-=1
return res
最外层采用for循环,内部嵌套双指针:
- 首先将数组nums进行排序,然后遍历数组nums:
- 如果当前元素大于0,直接返回结果res;如果当前元素和其前一个元素相同,continue;
- 令指针left指向当前元素的后一项,指针right指向数组的最后一个元素;
- 当left小于right时:
- 计算三个元素的和sum;如果sum大于0,说明right指针应该向左移;如果sum小于0,说明left指针应该向右移;如果sum等于0,找到符合题意的三个元素,将其加入res结果集,并应该将left指针向右移、将right指针向左移,移至第一个与其自身不同的元素上
class Solution(object):
def threeSum(self, nums):
nums.sort()
n=len(nums)
res=[]
for i in range(n):
if nums[i]>0:return res
if i>0 and nums[i]==nums[i-1]:continue
left,right=i+1,n-1
while left<right:
sum=nums[i]+nums[left]+nums[right]
if sum>0:right-=1
elif sum<0:left+=1
else:
res.append([nums[i],nums[left],nums[right]])
while left<right and nums[left]==nums[left+1]:
left+=1
while left<right and nums[right]==nums[right-1]:
right-=1
left+=1
right-=1
return res
813

被折叠的 条评论
为什么被折叠?



