LeetCode刷题(python3)|day02 数组part02

情况:有点难,非暴力法看了视频讲解才能做出来

977.有序数组的平方
双指针法,用双指针从原数组两边依次挑选平方后最大的数放入新数组的最后

class Solution:
    def sortedSquares(self, nums: List[int]) -> List[int]:
        for i in range(0, len(nums)):
            nums[i] = nums[i] ** 2
        left = 0
        right = len(nums) - 1
        cur = right
        result = [0] * len(nums)
        while left <= right:
            if nums[left] > nums[right]:
                result[cur] = nums[left]
                left += 1
            else:
                result[cur] = nums[right]
                right -= 1
            cur -= 1
        return result

209.长度最小的子数组
用双指针维护一个滑动窗口。
首先动窗口尾部,当窗口内的和大于等于target时可以看看能不能更新最小窗口长度,然后动窗口的前端来缩小窗口长度

class Solution:
    def minSubArrayLen(self, target: int, nums: List[int]) -> int:
        end = 0
        curSum = 0
        result = len(nums) + 1
        start = 0
        while end < len(nums):
            curSum += nums[end]
            while curSum >= target:
                curLen = end - start  + 1
                result = curLen if curLen < result else result
                curSum -= nums[start]
                start += 1
            end += 1
        if result <= len(nums):
            return result
        else:
            return 0



59.螺旋矩阵II
分别处理上、右、下、左边时都是处理[)(左闭右开区间)来保证每处只被处理一次。
通过stratx、strary、offset来缩圈

class Solution:
    def generateMatrix(self, n: int) -> List[List[int]]:
        result = [[0 for _ in range(n)] for _ in range(n)]
        stratx = 0
        straty = 0
        offset = 1
        count = 1
        for _ in range(n//2):
            i = stratx
            j = straty
            while j < n - offset:
                result[i][j] = count        
                count += 1
                j += 1
            while i < n - offset:
                result[i][j] = count        
                count += 1
                i += 1
            while j >  offset - 1:
                result[i][j] = count        
                count += 1
                j -= 1       
            while i >  offset - 1:
                result[i][j] = count        
                count += 1
                i -= 1    
            stratx += 1
            straty += 1
            offset += 1
        if n % 2 != 0:
            result[n//2][n//2] = count
        return result  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值