Subarray Sum K
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的更多相关文章
- [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 ...
- 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 ...
- [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 ...
- [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 ...
- [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 ...
- 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 ...
- 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 ...
- Subarray Sum Equals K LT560
Given an array of integers and an integer k, you need to find the total number of continuous subarra ...
- [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 ...
随机推荐
- mac 彻底卸载Paragon NTFS
之前安装了paragon NTFS,试用期过了就卸载了,但是每天还是会提示“试用期已到期”,看着很烦. 百度了一下,发现网上的版本可能比较老了,和我的情况不太一样,但道理应该是一样的. 彻底删除方法: ...
- session跨域共享
www.maxomnis.com的index.php文件内容 <?phpsession_start();setcookie("user", "alex proter ...
- JavaPersistenceWithHibernate第二版笔记-第六章-Mapping inheritance-006Mixing inheritance strategies(@SecondaryTable、@PrimaryKeyJoinColumn、<join fetch="select">)
一.结构 For example, you can map a class hierarchy to a single table, but, for a particular subclass, s ...
- 对private protected public的详解:
#include <iostream> #include <stack> #include <queue> #include <exception> # ...
- p3163 [CQOI2014]危桥
传送门 分析 代码 #include<iostream> #include<cstdio> #include<cstring> #include<string ...
- 51NOD 1616 最小集合
传送门 分析 不难发现集合中的数一定是集合内其它一堆数的$gcd$ 于是我们枚举$i$,统计原来集合中有几个数是$i$的倍数,设这个值为$f(i)$ 之后对于每个$i$如果不存在$f(x*i) = f ...
- python3-password在输入密码时隐藏密码
# Auther: Aaron Fan #这个脚本请在命令行去执行才可以试出效果,pycharm这里无法测试这个脚本,切记!import getpass _username = "Aaron ...
- 1.6 opencv视频操作基础
利用opencv中的VideoCapture类,来对视频进行读取显示,以及调用摄像头. VideoCapture是opencv 2.X中新增的一个类,对应于之前C语言版本的CvCapture结构体.它 ...
- HUB和Switch
http://baike.baidu.com/view/600161.htm 当然交换机的功能还不止如此,它可以把网络拆解成网络分支.分割网络数据流,隔离分支中发生的故障,这样就可以减少每个网络分支的 ...
- GitHub Pages搭建博客HelloWorld版
1.原理 GitHub作为博客相关文件的托管方,你把按照jekyll规定的目录及文件上传至github库中,通过约定的库名称即可访问到经过jekyll渲染后的博客页面. 2.搭建过程 2.1.注册Gi ...