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

     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.

    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).

    Credits:
    Special thanks to @Freezen for adding this problem and creating all test cases.

    https://leetcode.com/problems/minimum-size-subarray-sum/solution/
    链接中给出的解答非常全面,暴力搜索会导致超时,用空间换时间会使得时间复杂度降低到n^2,通过使用二叉搜索可以使得复杂度进一步降低,这道题最好的方法是使用双指针,分别表示子序列的头和尾,遍历整个数组,sum表示之前所有元素之和,内部的while循环则每次去除下表最小的元素,逐步找到最短的符合要求子序列,最后结果返回ans

    要点:贪心算法
    伪代码如下:
    1、初始化left = 0, sum = 0
    2、for i = 0 to n 循环
    sum累加
    计算符合要求的子序列的长度,跟新ans

    ps:最开始我也怀疑这么做能否找到最优解,后来仔细想了一下,这样做可以遍历所有的恰好满足要求的连续子数组,必定会找到最优解。

     1 int minSubArrayLen(int s, vector<int>& nums)
     2 {
     3     int n = nums.size();
     4     int ans = INT_MAX;
     5     int left = 0;
     6     int sum = 0;
     7     for (int i = 0; i < n; i++) {
     8         sum += nums[i];
     9         while (sum >= s) {
    10             ans = min(ans, i + 1 - left);
    11             sum -= nums[left++];
    12         }
    13     }
    14     return (ans != INT_MAX) ? ans : 0;
    15 }

    时间复杂度:O(n),每个元素最多被左右两个指针遍历两次。

    空间复杂度:O(1)

    二刷,笔写,2018-03-14,看着解释基本AC

  • 相关阅读:
    使用 kubeadm 部署 v1.18.5 版本 Kubernetes 集群
    MHA高可用主从复制实现
    基于Keepalived高可用集群的MariaDB读写分离机制实现
    MariaDB主从半同步复制详解
    postman学习网址
    程序员的脑子是更新换代最快的
    带组装3ROS_1节点_192通道
    带组装4ROS_1节点_256通道
    带组装5ROS_1node_320Chan
    带组装7ROS_1节点_448通道
  • 原文地址:https://www.cnblogs.com/dapeng-bupt/p/8566105.html
Copyright © 2011-2022 走看看