977.有序数组的平方
class Solution:
def sortedSquares(self, nums: List[int]) -> List[int]:
# create two pointers at the beginnig and end
# compare the numbers from these two pointers, square the larger ones into new array
# shift the pointer after operation
# Stop when left = right
result = [0] * len(nums)
left = 0
right = len(nums)-1
for end in range(len(nums)-1, -1, -1):
if abs(nums[left])>= abs(nums[right]):
result[end]=nums[left]*nums[left]
left+=1
else:
result[end]=nums[right]*nums[right]
right -=1
return result
This question is relative easy once master the concept of two pointer
209.长度最小的子数组

![]()

文章描述了一种算法,通过在有序数组中运用两指针技巧,找到使得所有元素平方和最小的子数组。Solution类中的sortedSquares函数实现这一过程,从数组两端开始比较并逐步调整指针位置。
288

被折叠的 条评论
为什么被折叠?



