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]]