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 ...
随机推荐
- MarkdownPad 2 安装和破解
MarkdownPad 2 安装和破解 下载:http://markdownpad.com/ 下载下面这个: 破解:http://w3cboy.com/post/2014/10/MarkdownPad ...
- boost::thread 库的使用
转载自:http://blog.csdn.net/yockie/article/details/9181939 概要 通过实例介绍boost thread的使用方式,本文主要由线程启动.Interru ...
- 1、awk打开多个文件的方法
转载:http://www.cnblogs.com/Berryxiong/p/6209324.html 1.当awk读取的文件只有两个的时候,比较常用的有三种方法(1)awk 'NR==FNR{... ...
- Python 使用其他邮件服务商的 SMTP 访问(QQ、网易、163、Google等)发送邮件
163邮箱SMTP授权 使用Python SMTP发送邮件 # -*- coding:utf-8 -*- from __future__ import print_function __author_ ...
- loj10104 [POI 2008]Blockade
传送门 分析 我们知道对于一个割点,我们如果去掉它就会使原来的图被分为若干块,则这是我们将所有块包含的点的个数两两相乘即可,而如果不是割点则对于图的连通性没有影响.注意在最后要加上2*(n-1)表示去 ...
- Git 之 协同开发
GitHub中多人协同开发和单人开发还是有点差别,协同开发一般有两种方式: 合作者,将其他用户添加到仓库合作者中之后,该用户就具有向当前仓库提交代码. 组织,创建一个组织,然后再该组织下可以创建多个项 ...
- Ubuntu16.04版安装VMwareTools的步骤和没法挂载目录问题的解决
vmtool安装流程 1.点击vmware 里面的虚拟机——>安装vmware tool 2.然后(等待一会)弹出一个界面把里面的 VMwareTools-9.6.1-1378637.tar.g ...
- [译]我们应该在HTML文档中何处放script标签
本文翻译youtube上的up主kudvenkat的javascript tutorial播放单 源地址在此: https://www.youtube.com/watch?v=PMsVM7rjupU& ...
- 将Winform程序及dll打包成可执行的exe
使用场景 通常开发的Winform程序,引用了其他类库后,在输出目录下都会产生很多DLL文件,exe执行时必须依赖这些DLL.想要Winform程序只有一个可执行exe文件,又不想打包成安装包,就可以 ...
- javascript 字典类型的使用
javascript 字典类型的使用 1.使用Array: var arr = new Array(); arr["zs"] = "zhangsan"; ar ...