Zero Sum Subarray
Given an integer array, find a subarray where the sum of numbers is zero.
Your code should return the index of the first number and the index of the last number. Example
Given [-, , , -, ], return [, ] or [, ]. Note
There is at least one subarray that it's sum equals to zero.
题解1 - 两重 for 循环
题目中仅要求返回一个子串(连续)中和为0的索引,而不必返回所有可能满足题意的解。最简单的想法是遍历所有子串,判断其和是否为0,使用两重循环即可搞定,最坏情况下时间复杂度为 O(n^2), 这种方法显然是极其低效的,极有可能会出现 TLE. 下面就不浪费篇幅贴代码了。
题解2 - 比较子串和(TLE)
两重 for 循环显然是我们不希望看到的解法,那么我们再来分析下题意,题目中的对象是分析子串和,那么我们先从常见的对数组求和出发,f(i) 表示从数组下标 0 开始至下标 i 的和。子串和为0,也就意味着存在不同的 i1 和 i2 使得 f(i1)−f(i2)=0, 等价于 f(i1)=f(i2). 思路很快就明晰了,使用一 vector 保存数组中从 0 开始到索引i的和,在将值 push 进 vector 之前先检查 vector 中是否已经存在,若存在则将相应索引加入最终结果并返回。
C++:
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){
vector<int> result;
int curr_sum = ;
vector<int> sum_i;
for (int i = ; i != nums.size(); ++i) {
curr_sum += nums[i];
if ( == curr_sum) {
result.push_back();
result.push_back(i);
return result;
}
vector<int>::iterator iter = find(sum_i.begin(), sum_i.end(), curr_sum);
if (iter != sum_i.end()) {
result.push_back(iter - sum_i.begin() + );
result.push_back(i);
return result;
}
sum_i.push_back(curr_sum);
}
return result;
}
};
源码分析
使用curr_sum保存到索引i处的累加和,sum_i保存不同索引处的和。执行sum_i.push_back之前先检查curr_sum是否为0,再检查curr_sum是否已经存在于sum_i中。是不是觉得这种方法会比题解1好?错!时间复杂度是一样一样的!根本原因在于find操作的时间复杂度为线性。与这种方法类似的有哈希表实现,哈希表的查找在理想情况下可认为是 O(1).
复杂度分析
最坏情况下 O(n^2), 实测和题解1中的方法运行时间几乎一致。
题解3 - 哈希表
终于到了祭出万能方法时候了,题解2可以认为是哈希表的雏形,而哈希表利用空间换时间的思路争取到了宝贵的时间资源 :)
C++:
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){
vector<int> result;
// curr_sum for the first item, index for the second item
map<int, int> hash;
hash[] = ;
int curr_sum = ;
for (int i = ; i != nums.size(); ++i) {
curr_sum += nums[i];
if (hash.find(curr_sum) != hash.end()) {
result.push_back(hash[curr_sum]);
result.push_back(i);
return result;
} else {
hash[curr_sum] = i + ;
}
}
return result;
}
};
源码分析
为了将curr_sum == 0的情况也考虑在内,初始化哈希表后即赋予 <0, 0>. 给 hash赋值时使用i + 1, push_back时则不必再加1.
由于 C++ 中的map采用红黑树实现,故其并非真正的「哈希表」,C++ 11中引入的unordered_map用作哈希表效率更高,实测可由1300ms 降至1000ms.
复杂度分析
遍历求和时间复杂度为 O(n), 哈希表检查键值时间复杂度为 O(logL), 其中 L 为哈希表长度。如果采用unordered_map实现,最坏情况下查找的时间复杂度为线性,最好为常数级别。
题解4 - 排序
除了使用哈希表,我们还可使用排序的方法找到两个子串和相等的情况。这种方法的时间复杂度主要集中在排序方法的实现。由于除了记录子串和之外还需记录索引,故引入pair记录索引,最后排序时先按照sum值来排序,然后再按照索引值排序。如果需要自定义排序规则可参考sort_pair_second.
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){
vector<int> result;
if (nums.empty()) {
return result;
}
const int num_size = nums.size();
vector<pair<int, int> > sum_index(num_size + );
for (int i = ; i != num_size; ++i) {
sum_index[i + ].first = sum_index[i].first + nums[i];
sum_index[i + ].second = i + ;
}
sort(sum_index.begin(), sum_index.end());
for (int i = ; i < num_size + ; ++i) {
if (sum_index[i].first == sum_index[i - ].first) {
result.push_back(sum_index[i - ].second);
result.push_back(sum_index[i].second - );
return result;
}
}
return result;
}
};
源码分析
没啥好分析的,注意好边界条件即可。这里采用了链表中常用的「dummy」节点方法,pair排序后即为我们需要的排序结果。这种排序的方法需要先求得所有子串和然后再排序,最后还需要遍历排序后的数组,效率自然是比不上哈希表。但是在某些情况下这种方法有一定优势。
复杂度分析
遍历求子串和,时间复杂度为 O(n), 空间复杂度 O(n). 排序时间复杂度近似 O(nlogn), 遍历一次最坏情况下时间复杂度为 O(n). 总的时间复杂度可近似为 O(nlogn). 空间复杂度 O(n).
Zero Sum Subarray的更多相关文章
- Leetcode详解Maximum Sum Subarray
Question: Find the contiguous subarray within an array (containing at least one number) that has the ...
- [LintCode] Subarray Sum & Subarray Sum II
Subarray Sum Given an integer array, find a subarray where the sum of numbers is zero. Your code sho ...
- [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 ...
- [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 ...
- Subarray Sum K
Given an nonnegative integer array, find a subarray where the sum of numbers is k. Your code should ...
- [LeetCode] 560. Subarray Sum Equals K 子数组和为K
Given an array of integers and an integer k, you need to find the total number of continuous subarra ...
- Longest subarray of target sum
2018-07-08 13:24:31 一.525. Contiguous Array 问题描述: 问题求解: 我们都知道对于subarray的问题,暴力求解的时间复杂度为O(n ^ 2),问题规模已 ...
- maximum subarray problem
In computer science, the maximum subarray problem is the task of finding the contiguous subarray wit ...
- Leetcode: Max Sum of Rectangle No Larger Than K
Given a non-empty 2D matrix matrix and an integer k, find the max sum of a rectangle in the matrix s ...
随机推荐
- Opengl使用模型视图变换移动光源
光源绕一个物体旋转,按下鼠标左键时,光源位置旋转. #include <GL/glut.h> static int spin = 0;static GLdouble x_1 = 0.0;s ...
- 项目一:第十一天 2、运单waybill快速录入 3、权限demo演示-了解 5、权限模块数据模型 6、基于shiro实现用户认证-登录(重点)
1. easyui DataGrid行编辑功能 2. 运单waybill快速录入 3. 权限demo演示-了解 4. Apache shiro安全框架概述 5. 权限模块数据模型 6. 基于shiro ...
- 杭电ACM刷题(1):1002,A + B Problem II 标签: acmc语言 2017-05-07 15:35 139人阅读 评
最近忙于考试复习,没有多少可供自己安排的时间,所以我利用复习之余的空闲时间去刷刷杭电acm的题目,也当对自己编程能力的锻炼吧. Problem Description I have a very si ...
- 前端(HTML/CSS/JS)-CSS编码规范
1. 文件名规范 文件名建议用小写字母加中横线的方式.为什么呢?因为这样可读性比较强,看起来比较清爽 https://stackoverflow.com/questions/25704650/disa ...
- MediaRecorder录像那些事
最近在做一个项目需要运用到MediaRecorder的API,之前都没接触过这部分,开始着手弄的时候各种各样的问题,真是让人崩溃呀! 最后通过网上的资料和大神的指点,当然也有自己几天坚持不懈的努力,终 ...
- Java50道经典习题-程序37 报数
题目:有n个人围成一圈,顺序排号.从第一个人开始报数(从1到3报数),凡报到3的人退出圈子,问最后留下的是原来第几号的那位.分析:最后留下的是第n号那位 import java.util.Scanne ...
- FineUI从iis6迁移到iis7.5上遇到的奇葩事情
前天把一台旧服务器上的windows2003+iis6上的fineui项目迁移到了win7+iis7上面来了,没有编译,直接以源码方式运行. 本来运行的好好的,昨天下午在上面用vs2010打开了一下看 ...
- String类-小用
字符串-string (1)string在Java中是一个引用类型,string变量可引用一个字符串对象 (2) 例1: s0,s1,s2引用同一个对象 New创建的两个string是不同的对象只是内 ...
- iOS工程师 - 简历
基本信息 姓 名:张学友 性 别:男 年 龄:28 学 历:本科 毕业学校:广西师范大学 专 业:通信工程 手 ...
- Codeforces Round #541 (Div. 2)D(并查集(dsu),拓扑排序)
#include<bits/stdc++.h>using namespace std;vector<int>g[2007];int fa[2007],vis[2007],num ...