LeetCode 209:最小長度的子數組 Minimum Size Subarray Sum

算法是一個程序的靈魂java

公衆號:愛寫bug(ID:icodebugs)python

做者:愛寫bug算法

給定一個含有 n 個正整數的數組和一個正整數 **s ,找出該數組中知足其和 ≥ s 的長度最小的連續子數組。**若是不存在符合條件的連續子數組,返回 0。數組

Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum ≥ s. If there isn't one, return 0 instead.debug

示例:指針

輸入: s = 7, nums = [2,3,1,2,4,3]
輸出: 2
解釋: 子數組 [4,3] 是該條件下的長度最小的連續子數組。

進階:code

若是你已經完成了O(n) 時間複雜度的解法, 請嘗試 O(n log n) 時間複雜度的解法。索引

Follow up:get

If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n).it

解題思路:

這裏咱們一步到位,直接用 O(n log n) 時間複雜度的解法。

​ 咱們定義兩個指針i、j,i 指向所截取的連續子數組的第一個數,j 指向連續子數組的最後一個數。截取從索引 i 到索引 j 的數組,該數組之和若小於 s,則 j 繼續後移,直到大於等於s。記錄 j 與 i 差值(返回的目標數)。以後i 後移一位繼續刷新新數組。

最壞狀況是 i 從0移動到末尾,時間複雜度爲O(n),內循環 j 時間複雜度O(log n),總時間複雜度 O(n log n) , 這道題 Java 提交運行時間:Your runtime beats 99.95 % of java submissions.

Java:

class Solution {
    public int minSubArrayLen(int s, int[] nums) {
        if(nums.length==0)return 0;//空數組則直接返回0
        //返回的目標數 target 定義爲最大,sum 起始值爲數組第一個數
        int i=0,j=0,numsLen=nums.length,target=Integer.MAX_VALUE,sum=nums[i];
        while (i<numsLen){
            while (sum<s){
                if(++j>=numsLen){//若是j等於numsLen,則sum已經是從索引i到末位的全部數字之和,後面i不管怎麼向後移動均不可能大於s,直接返回target
                    return target==Integer.MAX_VALUE ? 0:target;//若是target值依然爲Integer.MAX_VALUE,則意味着i=0,sum爲數組全部數之和,則返回0
                }else {
                    sum+=nums[j];//sum向後累加直到大於s
                }
            }
            if(j-i+1<target) target=j-i+1;//刷新target的值
            sum-=nums[i++];//sum移去i的值獲得新數組之和,i進一位
        }
        return target;
    }
}

Python3:

class Solution:
    def minSubArrayLen(self, s: int, nums: List[int]) -> int:
        if len(nums)==0: return 0
        i = 0
        j = 0
        nums_len = len(nums)
        target = float("inf")#將target定義爲最大
        sum = nums[0]
        while i < nums_len:
            while sum < s:
                j+=1
                if j >= nums_len:
                    return target if target != float("inf") else 0
                else:
                    sum += nums[j]
            target = min(target, j - i + 1)
            sum -= nums[i]
            i+=1
        return target

相關文章
相關標籤/搜索