2023-01-29 第二天

2023-01-28  本文已影响0人  远方的飞鱼
977.有序数组的平方

题目建议: 本题关键在于理解双指针思想

题目链接:https://leetcode.cn/problems/squares-of-a-sorted-array/

文章讲解:https://programmercarl.com/0977.%E6%9C%89%E5%BA%8F%E6%95%B0%E7%BB%84%E7%9A%84%E5%B9%B3%E6%96%B9.html

视频讲解: https://www.bilibili.com/video/BV1QB4y1D7ep

image.png
K = K -1 要放到判断外面,第一次来,不需要先有这个过程

双指针的解法:
简单总结就是 i,j 你追我赶的操作
class Solution:
def minSubArrayLen(self, target: int, nums: List[int]) -> int:

    i = 0

    nums_length = 0
    result  = float("inf")
    sum = 0

    for  j in range(len(nums)):

        sum += nums[j]

        # print("j = {} ,nums[j] = {},sum = {}".format(j,nums[j],sum))

        while sum >= target :

            nums_length = j - i + 1
            if result >= nums_length:



               print('i = {},j = {}'.format(i,j))
               result = nums_length

            sum = sum - nums[i]
            i = i + 1 
                
            
    if result == float("inf"):
       result = 0

    return result
上一篇 下一篇

猜你喜欢

热点阅读