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 + 1push_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的更多相关文章

  1. Leetcode详解Maximum Sum Subarray

    Question: Find the contiguous subarray within an array (containing at least one number) that has the ...

  2. [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 ...

  3. [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 ...

  4. [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 ...

  5. Subarray Sum K

    Given an nonnegative integer array, find a subarray where the sum of numbers is k. Your code should ...

  6. [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 ...

  7. Longest subarray of target sum

    2018-07-08 13:24:31 一.525. Contiguous Array 问题描述: 问题求解: 我们都知道对于subarray的问题,暴力求解的时间复杂度为O(n ^ 2),问题规模已 ...

  8. maximum subarray problem

    In computer science, the maximum subarray problem is the task of finding the contiguous subarray wit ...

  9. 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 ...

随机推荐

  1. UIScrollView现实循环滚动

    #import "RootViewController.h" #define width [UIScreen mainScreen].bounds.size.width #defi ...

  2. 关于MySQL隐式转换

    一.如果表定义的是varchar字段,传入的是数字,则会发生隐式转换. 1.表DDL 2.传int的sql 3.传字符串的sql 仔细看下表结构,rid的字段类型: 而用户传入的是int,这里会有一个 ...

  3. p1627 [CQOI2009]中位数

    传送门 分析 https://www.luogu.org/blog/user43145/solution-p1627 代码 #include<iostream> #include<c ...

  4. 带有通配符的字符串匹配算法-C/C++

    日前某君给我出了这样一道题目:两个字符串,一个是普通字符串,另一个含有*和?通配符,*代表零个到多个任意字符,?代表一个任意字符,通配符可能多次出现.写一个算法,比较两个字符串是否相等. 我花了四个小 ...

  5. PLSQL连接Oracle11g 64位

    目前plsql只有32位的,而Oracle11则是64位的,想要连接需要下载这个: 打开plsql,在Tools-->Prefences里面设置,如下图: 设置Oracle的主目录:下载文件解压 ...

  6. C#检测系统是否激活[转自StackOverFlow]

    using System; using System.Collections.Generic; using System.Text; using System.Runtime.InteropServi ...

  7. 动态变更GridView控件列名

    近段时间,确是很多专案要写,客户的个性化要求也越来越多.举个例子吧,就是从数据库取出来的字段名,在显示在GridView时,需要全部更为另外一个名称.下面的样例,并非是专案的内容,而是Insus.NE ...

  8. JS控制A标记的href跳转

    var a = document.getElementById("aHref"); a.href = '/user'; //取消<a>标签原先的onclick事件,使& ...

  9. c++标准库介绍

    C++标准库的所有头文件都没有扩展名.C++标准库的内容总共在50个标准头文件中定义,其中18个提供了C库的功能.<cname>形式的标准头文件[<complex>例外]其内容 ...

  10. 转载Json和Xml的区别,以及它们的底层是如何处理的

    XML:可扩展标记语言       JSON:轻量级的数据交换格式 区别: 1.可读性方面:基本相同,Xml的可读性较好些: 2.可扩展性方面:都有较好的扩展性: 3.编码难度方面:json的编码较容 ...