03-2021-01-13 leetcode

博客提及三个经典算法问题,包括盛水最多容器问题、最长公共前缀问题以及三数之和相加为0的问题,这些均为信息技术领域常见的算法挑战。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

11.盛水最多容器

class Solution:
    def maxArea(self, height: List[int]): -> int:\
        left = 0
        right = len(height) - 1
        while left<right:
            area = min(height[left], height[right]) * (right - left)
            ans = max(ans, area)
            if height[left]<= height[right]:
                left += 1
            else:
                right -= 1
        return ans

14.最长公共前缀

class solution:
    def longestCommonPrefix(self, strs:List[str]) -> str:
        if not strs:
            return ""
        length, count = len(str[0]), len(strs)
        for i in range(length):
            c = strs[0][i]
            if any(i == len(strs[j]) or strs[j][i] != c for j in range(1, count)):
                return strs[0][:i]
        return strs[0]

15.三数之和相加为0

class solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        n = len(nums)
        nums.sort()
        ans = list()

        #枚举a
        for first in range(n):
            if first > 0 and nums[first] == nums[first - 1]:
                continue
                #c对应的指针初始指向数组最右端
                third = n-1
                target = -nums[first]
                #枚举b
                for second in range(first + 1, n):
                    if second > first+1 and nums[second] == nums[second - 1]:
                        continue
                    while second < third and nums[second] + nums[third] > target:
                        third -= 1
                    if second == third:
                        break
                    if nums[second] + nums[third] = target:
                        ans.append([nums[first], nums[second], nums[third])
        return ans
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值