• 209 minimum size subarray sum


    大于或等于给定值  长度最小的子数组 

    leetcode 209

    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.

    ===========

    给定一个整数数组int a[] = {2,3,1,2,4,3},给定一个整数数字s;

    求在a中子数组累加和 大于等于s中,长度最小的子数组长度;否则返回0;

    一种时间复杂度o(n)的算法。

    ==========

    思路:两个指针的思路,

    start指向目标数组的开始位置,

    i指向待查找位置,

    [start,i]组成了当前数组已经发现的子数组,子数组可能会随着i一直扩大,

    tsum表示子数组的元素和,如果tsum>s说明发现一个解,记下现在子数组的长度[i-start+1]

    ===========

    code:

    class A{
      public:
       int minSubArrayLen(int s, vector<int>& nums) {
            int start = 0;
            int minlen = INT_MAX;
            int tsum = 0;
            for(int i = 0;i<(int)nums.size();i++){
                tsum +=nums[i];
                while(tsum >= s){
                    minlen = min(minlen,i-start+1);
                    tsum = tsum - nums[start++];///关键是这一步,当tsum>=3是,start下标一直前进,而i下标是不变的
                }
            }
            return minlen==INT_MAX? 0: minlen;
        }
    };
  • 相关阅读:
    大数据学习——三大组件总结
    js获取当前时间的前一天/后一天
    Windows下主机名和IP映射设置
    大数据学习——HDFS的shell
    微服务化架构特征
    Spring cloud consul 相关前提知识
    Kubeadm 安装
    remove docker ce fully on centos7
    Jquery Gritter set position
    Toggle Checkboxes on/off
  • 原文地址:https://www.cnblogs.com/li-daphne/p/5550834.html
Copyright © 2020-2023  润新知