leetcode day 2

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值