Given an nonnegative integer array, find a subarray where the sum of numbers is k.
Your code should return the index of the first number and the index of the last number. Example
Given [1, 4, 20, 3, 10, 5], sum k = 33, return [2, 4].

题解1 - 哈希表

题 Zero Sum Subarray | Data Structure and Algorithm 的升级版,这道题求子串和为 K 的索引。首先我们可以考虑使用时间复杂度相对较低的哈希表解决。前一道题的核心约束条件为 f(i1)−f(i2)=0,这道题则变为 f(i1)−f(i2)=k

C++:

#include <iostream>
#include <vector>
#include <map> using namespace std; class Solution {
public:
/**
* @param nums: A list of integers
* @return: A list of integers includes the index of the first number
* and the index of the last number
*/
vector<int> subarraySum(vector<int> nums, int k){
vector<int> result;
// curr_sum for the first item, index for the second item
// unordered_map<int, int> hash;
map<int, int> hash;
hash[] = ; int curr_sum = ;
for (int i = ; i != nums.size(); ++i) {
curr_sum += nums[i];
if (hash.find(curr_sum - k) != hash.end()) {
result.push_back(hash[curr_sum - k]);
result.push_back(i);
return result;
} else {
hash[curr_sum] = i + ;
}
} return result;
}
}; int main(int argc, char *argv[])
{
int int_array1[] = {, , , , , };
int int_array2[] = {, , , , , , };
vector<int> vec_array1;
vector<int> vec_array2;
for (int i = ; i != sizeof(int_array1) / sizeof(int); ++i) {
vec_array1.push_back(int_array1[i]);
}
for (int i = ; i != sizeof(int_array2) / sizeof(int); ++i) {
vec_array2.push_back(int_array2[i]);
} Solution solution;
vector<int> result1 = solution.subarraySum(vec_array1, );
vector<int> result2 = solution.subarraySum(vec_array2, ); cout << "result1 = [" << result1[] << " ," << result1[] << "]" << endl;
cout << "result2 = [" << result2[] << " ," << result2[] << "]" << endl; return ;
}

输出:

result1 = [ ,]
result2 = [ ,]

源码分析

与 Zero Sum Subarray 题的变化之处有两个地方,第一个是判断是否存在哈希表中时需要使用hash.find(curr_sum - k), 最终返回结果使用result.push_back(hash[curr_sum - k]);而不是result.push_back(hash[curr_sum]);

复杂度分析

略,见 Zero Sum Subarray | Data Structure and Algorithm

题解2 - 利用单调函数特性

不知道细心的你是否发现这道题的隐含条件——nonnegative integer array, 这也就意味着子串和函数 f(i) 为「单调不减」函数。单调函数在数学中可是重点研究的对象,那么如何将这种单调性引入本题中呢?不妨设 i2>i1, 题中的解等价于寻找 f(i2)−f(i1)=k, 则必有 f(i2)≥k.

我们首先来举个实际例子帮助分析,以整数数组 {1, 4, 20, 3, 10, 5} 为例,要求子串和为33的索引值。首先我们可以构建如下表所示的子串和 f(i).

f(i) 1 5 25 28 38
i 0 1 2 3 4

要使部分子串和为33,则要求的第二个索引值必大于等于4,如果索引值再继续往后遍历,则所得的子串和必大于等于38,进而可以推断出索引0一定不是解。那现在怎么办咧?当然是把它扔掉啊!第一个索引值往后递推,直至小于33时又往后递推第二个索引值,于是乎这种技巧又可以认为是「两根指针」。

C++:

#include <iostream>
#include <vector>
#include <map> using namespace std; class Solution {
public:
/**
* @param nums: A list of integers
* @return: A list of integers includes the index of the first number
* and the index of the last number
*/
vector<int> subarraySum2(vector<int> &nums, int k){
vector<int> result; int left_index = , curr_sum = ;
for (int i = ; i != nums.size(); ++i) {
while (curr_sum > k) {
curr_sum -= nums[left_index];
++left_index;
} if (curr_sum == k) {
result.push_back(left_index);
result.push_back(i - );
return result;
}
curr_sum += nums[i];
}
return result;
}
}; int main(int argc, char *argv[])
{
int int_array1[] = {, , , , , };
int int_array2[] = {, , , , , , };
vector<int> vec_array1;
vector<int> vec_array2;
for (int i = ; i != sizeof(int_array1) / sizeof(int); ++i) {
vec_array1.push_back(int_array1[i]);
}
for (int i = ; i != sizeof(int_array2) / sizeof(int); ++i) {
vec_array2.push_back(int_array2[i]);
} Solution solution;
vector<int> result1 = solution.subarraySum2(vec_array1, );
vector<int> result2 = solution.subarraySum2(vec_array2, ); cout << "result1 = [" << result1[] << " ," << result1[] << "]" << endl;
cout << "result2 = [" << result2[] << " ," << result2[] << "]" << endl; return ;
}

输出:

result1 = [ ,]
result2 = [ ,]

源码分析

使用for循环, 在curr_sum > k时使用while递减curr_sum, 同时递增左边索引left_index, 最后累加curr_sum。如果顺序不对就会出现 bug, 原因在于判断子串和是否满足条件时在递增之后(谢谢 @glbrtchen 汇报 bug)。

复杂度分析

看似有两重循环,由于仅遍历一次数组,且索引最多挪动和数组等长的次数。故最终时间复杂度近似为 O(2n), 空间复杂度为 O(1).

Subarray Sum K的更多相关文章

  1. [LeetCode] Maximum Size Subarray Sum Equals k 最大子数组之和为k

    Given an array nums and a target value k, find the maximum length of a subarray that sums to k. If t ...

  2. Subarray Sum & Maximum Size Subarray Sum Equals K

    Subarray Sum Given an integer array, find a subarray where the sum of numbers is zero. Your code sho ...

  3. [Locked] Maximum Size Subarray Sum Equals k

    Example 1: Given nums = [1, -1, 5, -2, 3], k = 3,return 4. (because the subarray [1, -1, 5, -2] sums ...

  4. [LeetCode] Subarray Sum Equals K 子数组和为K

    Given an array of integers and an integer k, you need to find the total number of continuous subarra ...

  5. [Swift]LeetCode325. 最大子数组之和为k $ 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 ...

  6. Subarray Sum & Maximum Size Subarray Sum Equals K && Subarray Sum Equals K

    Subarray Sum Given an integer array, find a subarray where the sum of numbers is zero. Your code sho ...

  7. Maximum Size Subarray Sum Equals k LT325

    Given an array nums and a target value k, find the maximum length of a subarray that sums to k. If t ...

  8. Subarray Sum Equals K LT560

    Given an array of integers and an integer k, you need to find the total number of continuous subarra ...

  9. [leetcode]523. Continuous Subarray Sum连续子数组和(为K的倍数)

    Given a list of non-negative numbers and a target integer k, write a function to check if the array ...

随机推荐

  1. NSButton添加事件

    -(void)addButton { NSButton* pushButton = [[NSButton alloc] initWithFrame: NSMakeRect(, , , )]; push ...

  2. 2015年阿里实习生面试Java研发工程师 小记

    5月5日,广州,阿里实习生面试,Java研发工程师,完全被虐orz 几乎没有Java项目开发经验,接近零基础,去水了一发,毫无悬念的被刷了..RP也是杠杠的,准备过的题目一个都没被问到,算法题也是一条 ...

  3. 前端(HTML/CSS/JS)-JavaScript编码规范

    1. 变量命名 (1)变量名不应以短巧为荣 左边的变量名都不太清楚,代码的扩展性不好,一旦代码需要加功能的话,就容易出现obj1.obj2.obj3这种很抽象的命名方式.所以一开始就要把变量的名字起得 ...

  4. wordcount小程序

    wordcount小程序 (1)github网址 https://github.com/yuyuyu960818/count_txt_file (2)PSP表 PSP2.1 PSP阶段 预估耗时 (分 ...

  5. 在WindowsXP+IIS5.1下运行ASP.NET MVC3

    1. 安装ASP.NET MVC3 http://download.microsoft.com/download/1/4/C/14C0533D-2299-42CD-898C-10AA5156E243/ ...

  6. 2 plan team 服务器搭建

    最近想搞个2-plan team看看,是不是适合小型团队任务管理 下了个包,解压了,发现里面的readme太简单了 readme中的install相关的内容如下 ### Installation in ...

  7. 【bzoj2434】: [Noi2011]阿狸的打字机 字符串-AC自动机-BIT

    [bzoj2434]: [Noi2011]阿狸的打字机 x串在y串上的匹配次数就是y在自动机所有节点上能够通过fail走到x最后一个节点的个数 (就是y串任意一个前缀的后缀能匹配到x的个数)和[bzo ...

  8. loj #2006. 「SCOI2015」小凸玩矩阵

    #2006. 「SCOI2015」小凸玩矩阵   题目描述 小凸和小方是好朋友,小方给小凸一个 N×M N \times MN×M(N≤M N \leq MN≤M)的矩阵 A AA,要求小凸从其中选出 ...

  9. C++基础学习1: C++布尔类型

    布尔类型(bool)是C++新增的一种基本数据类型.在标准的C语言中并未定义bool类型,如果需要使用bool类型, 程序员可以通过宏定义来自定义一个bool类型,定义语句如下: #define bo ...

  10. [USACO08NOV]安慰奶牛Cheering up the Cow BZOJ 1232 Kruskal

    Farmer John变得非常懒, 他不想再继续维护供奶牛之间供通行的道路. 道路被用来连接N (5 <= N <= 10,000)个牧场, 牧场被连续地编号为1..N. 每一个牧场都是一 ...