LeetCode腾讯精选练习50——第三天

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

class Solution:
    def maxArea(self, height: List[int]) -> int:
        """
        :type height: List[int]
        :rtype: int
        """
        left = 0
        right = len(height) - 1
        maxArea = 0
        while left < right:
            b = right - left
            if height[left] < height[right]:
                h = height[left]
                left += 1
            else:
                h = height[right]
                right -= 1
            area = b*h
            if maxArea < area:
                maxArea = area
        return maxArea

运行结果:

题目14:最长公共前缀
编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 “”。
题解:

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        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

运行结果:
在这里插入图片描述
题目15:三数之和
给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有和为 0 且不重复的三元组。
注意:答案中不可以包含重复的三元组。
题解:

class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        # 将nums分成三组:zeros,positives,negatives
        zeros, positives, negatives = 0, {
    
    }, {
    
    }
        for num in nums:
            if num == 0:
                zeros += 1
            elif num > 0:
                positives.setdefault(num, 0)
                positives[num] += 1
            else:
                negatives.setdefault(num, 0)
                negatives[num] += 1

        # 相加为0的三元组可能的组成形式:
        # 3个0,两个负数一个正数,两个正数一个负数,一正一负加一零
        results = []
        if zeros >= 3:
            results.append([0] * 3)
            
        if len(positives) != 0 and len(negatives) != 0:
            for pi in positives:
                count = positives[pi]
                if count >= 2 and (-2 * pi) in negatives:
                    results.append([pi] * 2 + [-2 * pi])
                if -pi in negatives and zeros > 0:
                    results.append([pi, -pi, 0])
                for pj in positives:
                    if pj <= pi:
                        continue
                    if -1 * (pi + pj) in negatives:
                        results.append([-1 * (pi + pj), pi, pj])
    
            for ni in negatives:
                count = negatives[ni]
                if count >= 2 and (-2 * ni) in positives:
                    results.append([ni] * 2 + [-2 * ni])
                for nj in negatives:
                    if nj <= ni:
                        continue
                    if -1 * (ni + nj) in positives:
                        results.append([-1 * (ni + nj), ni, nj])

        return results

运行结果:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_44315884/article/details/112596463