zoukankan      html  css  js  c++  java
  • Minimum Size Subarray Sum

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

    For example, given the array [2,3,1,2,4,3] and s = 7,
    the subarray [4,3] has the minimal length under the problem constraint.

    click to show more practice.

    More practice:

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

    注意:求的是连续子数组

    1.o(n)

    class Solution {
    public:
        int minSubArrayLen(int s, vector<int>& nums) {
            int numsSize = nums.size();
            int i=-1,j=0;
            int sum=0;
            int minLen = numsSize+1;
            while(i<j){
                if(sum<s){
                    if(j>=numsSize){
                        break;
                    }
                    sum+=nums[j++];
                }else if(sum>=s){
                    minLen = min(minLen,j-i-1);
                    sum-=nums[++i];
                }
            }
            return minLen==numsSize+1 ? 0:minLen;
        }
    };

     2.o(nlgn)

    class Solution {
    public:
        int minSubArrayLen(int s, vector<int>& nums) {
            int numsSize = nums.size();
            int low = 0,high=numsSize+1;
            while(low<high){
                int mid = low+(high-low)/2;
                int sum = 0;
                for(int i=0;i<numsSize;i++){
                    sum+=nums[i];
                    if(i>=mid){
                        sum-=nums[i-mid];
                    }
                    if(sum>=s){
                        break;
                    }
                }
                if(sum>=s){
                    high = mid;
                }else{
                    low = mid+1;
                }
            }
            return low==numsSize+1 ? 0:low;
        }
    };
  • 相关阅读:
    Leetcode#145 Binary Tree Postorder Traversal
    Leetcode#146 LRU Cache
    单引号和双引号的区别
    $* $@ $#
    pthread_detach
    pthread_join
    intent 启动activity、service的方法
    multicast based on udp
    ARM指令系统
    ARM寄存器
  • 原文地址:https://www.cnblogs.com/zengzy/p/5006540.html
Copyright © 2011-2022 走看看