有序数组平方和_长度最小的子数组_旋转矩阵II

977.有序数组的平方

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

  • Input: nums = [-4,-1,0,3,10]
  • Output: [0,1,9,16,100]
  • Explanation: After squaring, the array becomes [16,1,0,9,100].
  • After sorting, it becomes [0,1,9,16,100].
def sortedSquares(nums):
    i = 0
    j = len(nums)-1
    ans = [0 for t in range(j+1)]
    t = j
    while i<=j:
        if abs(nums[j]) > abs(nums[i]):
            ans[t] = nums[j]**2
            j-=1
        else:
            ans[t] = nums[i]**2
            i+=1
        t -= 1
    return ans
sortedSquares([-4,-1,0,3,10])
[0, 1, 9, 16, 100]

长度最小的子数组

Given an array of positive integers nums and a positive integer target

return the minimal length of a contiguous subarray [numsl, numsl+1, …, numsr-1, numsr] of which the sum is greater than or equal to target. If there is no such subarray, return 0 instead.

  • Input: target = 7, nums = [2,3,1,2,4,3]

  • Output: 2

  • Explanation: The subarray [4,3] has the minimal length under the problem constraint.

  • Input: target = 11, nums = [1,1,1,1,1,1,1,1]

  • Output: 0

def Minimum_Size_Subarray(nums, target):
    i = 0
    length = float('inf')
    temp = 0
    for j in range(len(nums)):
        temp += nums[j]
        while temp >= target:
            length = min(length, j-i+1)
            temp -= nums[i]
            i += 1
    return length if length != float('inf') else 0
Minimum_Size_Subarray([2,3,1,2,4,3], 7)
2

59:旋转矩阵

Given a positive integer n, generate an n x n matrix filled with elements from 1 to n2 in spiral order.

在这里插入图片描述

def Spiral_Matrix(n):
    Matrix = [[0 for i in range(n)] for j in range(n)]
    start_x, start_y = 0, 0
    loop, mid = n//2, n//2
    count = 1
    
    for offset in range(1, loop+1):
        for i in range(start_y, n-offset):
            Matrix[start_x][i] = count
            count+=1
        for i in range(start_x, n-offset):
            Matrix[i][n-offset] = count
            count+=1
        for i in range(n-offset, start_y, -1):
            Matrix[n-offset][i] = count
            count+=1
        for i in range(n-offset, start_x, -1):
            Matrix[i][start_y] = count
            count+=1
        
        start_x += 1
        start_y += 1
        
    if n%2 != 0:
        Matrix[mid][mid] = count
    return Matrix
        
Spiral_Matrix(4)
[[1, 2, 3, 4], [12, 13, 14, 5], [11, 16, 15, 6], [10, 9, 8, 7]]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值