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 ...
随机推荐
- ROS Learning-022 learning_tf-06(编程) 现在与过去中穿梭 (Python版) --- waitForTransformFull() 函数
ROS Indigo learning_tf-06 现在与过去中穿梭 (Python版) - waitForTransformFull() 函数 我使用的虚拟机软件:VMware Workstatio ...
- R: 一页显示多张图的方法
################################################### 问题:一页多图显示 18.4.30 怎么实现,在一页上画多幅图,并且安排图的大小.个数等?? ...
- MySQL中的时间问题
MySQL 获得当前日期时间 函数 获得当前日期+时间(date + time)函数:now() mysql> select now(); +---------------------+ | n ...
- jQuery CSS 操作
jQuery CSS 操作 jQuery 拥有三种用于 CSS 操作的重要函数: $(selector).css(name,value) $(selector).css({properties}) $ ...
- How can I list colors in WPF with XAML?
How can I get list of all colors I can pick in Visual Studio Designer (which is System.Windows.Media ...
- C#数据类型及差异(复习专用)
一.数据类型 值类型 类型 描述 范围 默认值 bool 布尔值 True 或 False False byte 8 位无符号整数 0 到 255 0 char 16 位 Unicode 字符 U + ...
- ubuntu - 14.04,如何使用鼠标右键菜单在shell中打开选择项目?
在shell中执行:“sudo apt-get install nautilus-open-terminal”,随后重新启动系统,在要打开的文件夹上面鼠标右键,会有一个菜单项目“在终端中打开”,点击后 ...
- spoj Longest Common Substring
Longest Common Substring SPOJ - LCS 题意:求两个串的最长公共子串 /* 对一个串建立后缀自动机,用另一个串上去匹配 */ #include<iostream& ...
- Linux之sshkey密钥认证实战
在实际的生产环境中,经常会用到sshkey密钥认证实行数据分发数据等操作,还可以批量操作内网服务器,实行免密认证进行推送分发数据. 1.环境查看 分发服务器 节点服务器 2.服务器添加系统账号 3.生 ...
- (vue.js)import "mint-ui/lib/stylecss"失败
在vue2.0中引入了mint-ui后总是报一个css的错误 但是package.json中已经配置了css-loader style-loader ,webpack.config中也已经配置了css ...