Subarray Sum Equals K (O(n)时间复杂度)

原创 2018年04月17日 09:55:32

Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k.

Example 1:

Input:nums = [1,1,1], k = 2
Output: 2

最简单的想法是,遍历所有可能的子序列,分别求各个子序列的和。这样一来,可能的子序列有O(n^2)种,每种子序列求和又需要O(n)的复杂度。最终总的时间复杂度将达到O(n^3).

当然可以使用容器保存已经算好的前n个值的和,这样可以将总的时间复杂度降低到O(n^2).

要想达到时间限制要求,就需要使用O(n)的时间复杂度的算法。从头遍历数组,累加从第1个元素到第h个元素的值,按照h的下标将累加值存到map中(因为下标不连续)。这样,如果map(h-k)在map中存在,说明从h-k 到 h期间,肯定有元素的和刚好等于k。

        int cum=0; // cumulated sum
        map<int,int> rec; // prefix sum recorder
        int cnt = 0; // number of found subarray
        rec[0]++; // to take into account those subarrays that begin with index 0
        for(int i=0;i<nums.size();i++){
            cum += nums[i];
            cnt += rec[cum-k];
            rec[cum]++;
        }
        return cnt;

560. Subarray Sum Equals K leetcode

这道题,BF 时间复杂度O(n^2)public static int subarraySum(int[] nums, int k) { long [][] map = new lon...
  • meizum9zjl
  • meizum9zjl
  • 2017-05-11 22:46:51
  • 355

[leetcode] 560. Subarray Sum Equals K

Given an array of integers and an integer k, you need to find the total number of continuous subarra...
  • TstsUgeg
  • TstsUgeg
  • 2017-05-03 10:34:51
  • 2129

[leetcode] 325. Maximum Size Subarray Sum Equals k 解题报告

题目链接:https://leetcode.com/problems/maximum-size-subarray-sum-equals-k/ Given an array nums and a t...
  • qq508618087
  • qq508618087
  • 2016-03-06 05:50:30
  • 4003

[LeetCode325] Maximum Size Subarray Sum Equals k

Given an array nums and a target value k, find the maximum length of a subarray that sums to k. If t...
  • u012175043
  • u012175043
  • 2016-01-08 15:34:02
  • 1484

leetcode560. Subarray Sum Equals K

560. Subarray Sum Equals KGiven an array of integers and an integer k, you need to find the total nu...
  • rxt2012kc
  • rxt2012kc
  • 2017-06-25 14:03:03
  • 298

LeetCode 325. Maximum Size Subarray Sum Equals k(和为k的最长子数组)

原题网址:https://leetcode.com/problems/maximum-size-subarray-sum-equals-k/ Given an array nums and ...
  • jmspan
  • jmspan
  • 2016-04-26 06:10:18
  • 1073

LeetCode 560 : Subarray Sum Equals K(java)

本题求在一个数组中,连续子序列和为k的子序列(子序列长度为1-n均可,其中n为数组的大小)的个数。...
  • marlonlyh
  • marlonlyh
  • 2017-07-21 23:12:26
  • 340

20170603-leetcode-560-Subarray Sum Equals K

1.DescriptionGiven an array of integers and an integer k, you need to find the total number of conti...
  • u010105243
  • u010105243
  • 2017-06-03 16:16:06
  • 203

[leetcode 560]Subarray Sum Equals K

题目:求连续子集和为k的个数代码出自:https://discuss.leetcode.com/topic/88041/super-simple-pythonclass Solution(object...
  • lijjianqing
  • lijjianqing
  • 2017-05-18 15:13:18
  • 308

Subarray Sum Equals K

问题描述: Given an array of integers and an integer k, you need to find the total number of continu...
  • DDVAL
  • DDVAL
  • 2017-05-02 19:52:05
  • 355
收藏助手
不良信息举报
您举报文章:Subarray Sum Equals K (O(n)时间复杂度)
举报原因:
原因补充:

(最多只允许输入30个字)