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. c# 一维数组,二维数组,多维数组。

    数组就是给一个变量定义多个字符,可以是string也可以是int.或者说是一组变量. 可以更加方便的操作大量数据. 数组的定义1.数组里面的内容必须是同一类型2.数据必须有长度限制 一维数组 *一.数 ...

  2. 高性能MySQL笔记-第5章Indexing for High Performance-002Hash indexes

    一. 1.什么是hash index A hash index is built on a hash table and is useful only for exact lookups that u ...

  3. 339E Three Swaps

    传送门 题目大意 给出由1-n组成的序列,每次可将一个区间翻转.问如何从1-n的递增序列变成给出的序列,输出操作次数以及每次操作的区间.最多翻转3次,保证有解,输出任意方案即可. 分析 我们对于每一次 ...

  4. super-smack

    我有个办法,不过不是用LR,是用super-smack,如果只对数据库进行抗压力测试,应该管用.Super-smack 现在是1.3版,源码下载地址如下:http://vegan.net/tony/s ...

  5. Ubuntu学习小结(二)PostgreSQL的使用,进程的查看关闭,编辑器之神Vim入门

    距离上次发布文章已经过去了很久.在过去的半年中,虽然写的代码不多,但是在接触了计算机一些其他的知识,包括数据库.网络之后,感觉能够融会贯通,写代码水平又有了一定的提高.接下来,将会发表几篇文章,简单介 ...

  6. Bugly升级应用集成指南

    1.配置 app/build.gradle android { defaultConfig { ndk { //设置支持的SO库架构 abiFilters 'armeabi' //, 'x86', ' ...

  7. sql 根据指定字符截取前面几个字符

    1.找到指定字所在的位置并且减去多少是要截取的字符长度 CharIndex('元',product_name)-3) 2.截取 SUBSTRING(product_name, CharIndex('元 ...

  8. C# SendMessage用法一二

    函数功能:该函数将指定的消息发送到一个或多个窗口.此函数为指定的窗口调用窗口程序,直到窗口程序处理完消息再返回.而函数PostMessage不同,将一个消息寄送到一个线程的消息队列后立即返回.  函数 ...

  9. 单击GridView控件,高亮单击所在的记录行

    看过下面博文的网友,也许都会觉得有点遗憾,就是很难知道自己点击的是哪一记录行.http://www.cnblogs.com/insus/p/3211017.html 针对这个问题Insus.NET再对 ...

  10. Locust压力测试使用总结

    https://blog.csdn.net/jojoy_tester/article/details/77926470  参考网址 上次做接口压力测试前一直研究使用jmeter,本以为可以拿来使用了, ...