Tag2 977. Squares of a Sorted Array 209. Minimum Size Subarray Sum 59. Spiral Matrix II

文章介绍了三个数组操作的算法问题:1)给定非递减数组,返回平方后的排序数组;2)寻找大于等于目标和的最小子数组长度;3)生成螺旋顺序的矩阵。每个问题都讨论了不同的解决策略,如双指针、滑动窗口和循环判断。
摘要由CSDN通过智能技术生成

977. Squares of a Sorted Array

Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order.

1.Do not use ls = [0] or ls = [ ] when defining a new list. try to use ls = [float('inf')] and ls = [float('-inf')].

2.  sorted list :  left , right pointer

class Solution:
    def sortedSquares(self, nums: List[int]) -> List[int]:
        l = 0
        r = len(nums) - 1
        res = [float('inf')]*len(nums)
        i = len(nums) -1 #Fill the new list starting from the far right
        while l <= r: #it must have l = r this condition
            if nums[l]**2 > nums[r]**2:
                res[i] = nums[l]**2
                l += 1
            else:
                res[i] = nums[r]**2
                r -= 1
            i -= 1 
        return res

It is unwise to write i -= 1 below if and else condition. The while step condition can be written firstly at end.

nums is a non-decreasing oder, So the largest square value must be at the beginning or the end,for this reason we could think of using head and tail 2 pointers method.

If it doesn't going through l = r  this loop, the smallest value can't append to the new list ,so we only got null.

209. Minimum Size Subarray Sum

Given an array of positive integers nums and a positive integer target, return the minimal length of a subarray whose sum is greater than or equal to target. If there is no such subarray, return 0 instead.

1.sliding window : 2 times while loop

2.time limit exceeded:sum(nums[l : r+1])  .

                  replaced by : s += nums[r]  and s - = nums[l]

3.When to use while and when to use for:

     Using for if you know the set of elements or the number of repetitions to iterate over.
     If you don't know the end condition of the loop and need to judge whether to continue the loop based on the condition, use while .

4. Outer loop: the right pointer goes right all the way. sum+=nums【r】, r+=1
    Inner loop: when sum is greater than or equal to target. sum -= nums【l】, l +=1

5.Special case

class Solution:
    def minSubArrayLen(self, target: int, nums: List[int]) -> int:
        if sum(nums) < target:
            return 0

        l,r,s = 0,0,0
        
        m = float('inf')
        while r < len(nums):
            s += nums[r]
            while s >= target:#One step, two steps, three steps ....forward to the left
                m = min(r-l+1, m) #Each time the condition is met, a minimum value is obtained
                s -= nums[l]
                l += 1
            r += 1
        return m

59. Spiral Matrix II

Given a positive integer n, generate(生成,找到)an n x n matrix filled with elements from 1 to n**2 in spiral(旋转) order.

1.Minimal change per Loop

 2.  matrix definition method :nums = [[0] * n for _ in range(n)]

3. When n is odd, only the middle number remains : if n % 2 != 0:  nums[loop][loop] = count

it needs to be added outside the while loop.

4. for num in range(9, 0, -1):  987654321 don't write range(0, 9, -1)

5. Loop judgment:  while offset <= loop:

class Solution:
    def generateMatrix(self, n: int) -> List[List[int]]:
        start_x,start_y = 0, 0
        loop = n//2 #How many laps in total
        offset = 1 #which lap圈
        count = 1
        nums = [[0] * n for _ in range(n)]

        while offset <= loop:
            for j in range(start_y, n - offset):
                nums[start_x][j] = count
                count += 1
            for i in range(start_x, n - offset):
                nums[i][n - offset] = count #wrong:nums[i][start_y] = count
                count += 1
            for j in range(n - offset, start_y, -1):
                nums[n - offset][j] = count
                count += 1
            for i in range(n - offset, start_x, -1):
                nums[i][start_y] = count #wrong:nums[i][n - offset] = count
                count += 1
            
            start_x += 1
            start_y += 1
            offset += 1

        if n % 2 != 0:
            nums[loop][loop] = count
        
        return nums
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值