Day 2 数组 part 02

977. 有序数组的平方

        对于一个有序数组其两端的值才有可能是最大的值,因此只需要用双指针指示两端的值。

class Solution:
    def sortedSquares(self, nums: List[int]) -> List[int]:
        leftindex = 0
        rightindex = len(nums) - 1
        index = len(nums) - 1
        result = [float('inf')] * len(nums)
        while leftindex <= rightindex:
            if nums[leftindex]**2 < nums[rightindex]**2:
                result[index] = nums[rightindex]**2
                rightindex -= 1
            else:
                result[index] = nums[leftindex]**2
                leftindex += 1
            index -= 1
        return result

209. 长度最小的子数组

        不断滑动区间使得数组的和等于目标值,保留其中的最小值。

class Solution:
    def minSubArrayLen(self, target: int, nums: List[int]) -> int:
        leftindex, rightindex = 0,0
        min_length = float('inf')
        num_sum = 0
        while rightindex <= len(nums) - 1:
            num_sum += nums[rightindex]
            while num_sum >= target:
                min_length = min(min_length, rightindex - leftindex + 1)
                num_sum -= nums[leftindex]
                leftindex += 1
            rightindex += 1
        if min_length == float('inf'):
            return 0
        else:
            return min_length

59. 螺旋矩阵II

        洛谷做过这道题,就是模拟这个逻辑。

class Solution:
    def generateMatrix(self, n: int) -> List[List[int]]:
        nums = [[0] * n for _ in range(n)]
        startx, starty = 0, 0               
        loop, mid = n // 2, n // 2          
        count = 1                           
        for offset in range(1, loop + 1) :      
            for i in range(starty, n - offset) :   
                nums[startx][i] = count
                count += 1
            for i in range(startx, n - offset) :    
                nums[i][n - offset] = count
                count += 1
            for i in range(n - offset, starty, -1) : 
                nums[n - offset][i] = count
                count += 1
            for i in range(n - offset, startx, -1) : 
                nums[i][starty] = count
                count += 1                
            startx += 1         
            starty += 1

        if n % 2 != 0 :			
            nums[mid][mid] = count 
        return nums

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值