NO.10 盛最多水的容器(中等)

题目描述给定 n 个非负整数 a1a2,…,an,每个数代表坐标中的一个点 (iai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (iai) 和 (i, 0)。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。

说明:你不能倾斜容器,且 n 的值至少为 2。

图中垂直线代表输入数组 [1,8,6,2,5,4,8,3,7]。在此情况下,容器能够容纳水(表示为蓝色部分)的最大值为 49。

示例如下

输入: [1,8,6,2,5,4,8,3,7]
输出: 49

这个题目其实如果用遍历法非常的简单,可我忘记保存代码了。。。反正就四五行的样子,可一旦输入过长就会超过计算时间限制。所以我看了这个题目的阅读解答有关于这个题目的提示,在根据提示思考后,写的代码如下,打败了86%的人。

class Solution:
    def maxArea(self, height):
        """
        :type height: List[int]
        :rtype: int
        """
        maxarea=0
        start,end=0,len(height)-1
        while start<end:
            di=end-start
            if height[start]<height[end]:
                gao=height[start]
                start+=1
            else:
                gao=height[end]
                end-=1
            area=di*gao
            if area>maxarea:
                maxarea=area
        return maxarea

NO.11 三数之和(中等)

题目描述给定一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?找出所有满足条件且不重复的三元组。

注意:答案中不可以包含重复的三元组。

例如, 给定数组 nums = [-1, 0, 1, 2, -1, -4],

满足要求的三元组集合为:
[
  [-1, 0, 1],
  [-1, -1, 2]
]

这道题其实也是双指针的一道变式题,而且本题还有一个关键就是要不重复,具体代码见下:

class Solution:
    def threeSum(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        nums.sort()
        result=[]
        if len(nums)>=3 and nums[0]==nums[-1] and nums[-1]==0:#如果这里不写个这样的话,当元素很多且全是0的时候,会出错
            result.append((0,0,0)) 
            return result
        for i in range(len(nums)):
            if nums[i]>0:
                break
            target=0-nums[i]
            if i>0 and nums[i]==nums[i-1]: #如果这里不加个i>0会出现无法满足[0,0,0]的情况
                continue
            start,end=i+1,len(nums)-1
            while start<end:
                if nums[start]+nums[end]<target:
                    start+=1
                elif nums[start]+nums[end]>target:
                    end-=1
                else:
                    result.append((nums[i],nums[start],nums[end]))
                    start+=1
                    end-=1
                    while start<end and nums[start]==nums[start-1] :#这也是为了避免出现相同的情况
                        start+=1
                    while start<end and nums[end]==nums[end+1]:
                        end-=1
        return result
Pages: 1 2 3 4 5 6