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

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

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

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

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

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

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

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

  8. Subarray Sum Equals K LT560

    Given an array of integers and an integer k, you need to find the total number of continuous subarra ...

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

随机推荐

  1. Camera 3D概念

    1. integration time即积分时间是以行为单位表示曝光时间(exposure time)的,比如说INT TIM为159,就是指sensor曝光时间为159行,两者所代表的意思是相同的, ...

  2. vue 之 模板字符串

    传统的JavaScript语言,输出模板通常是这样的写的. $('#result').append( 'There are <b>' + basket.count + '</b> ...

  3. LeetCode第111题:二叉树的最小深度

    问题描述 给定一个二叉树,找出其最小深度. 最小深度是从根节点到最近叶子节点的最短路径上的节点数量. 说明: 叶子节点是指没有子节点的节点. 示例: 给定二叉树 [3,9,20,null,null,1 ...

  4. leetcode 6 ZigZag Converesion

    class Solution { public: string convert(string s, int nRows) { if (nRows <= 1) return s; string r ...

  5. C#根据弹窗标题获取窗体句柄并模拟点击按钮(FindWindow,FindWindowEx,SendMessage)

    任务:将下面弹窗自动关闭 /// <summary> /// 找到窗口 /// </summary> /// <param name="lpClassName& ...

  6. GetResponse() 基础连接已经关闭:服务器关闭了本应保持活动状态的连接

    1.原因: (1)KeepAlive默认为true,与internet保持持续连接 ,服务器关闭了连接,使用HttpWebResponse.GetResponse()出错 (2)HttpWebRequ ...

  7. Javascript-DOM笔记

    参考 javascript原生dom操作方法 JavaScript原生的dom操作方法 第一类:节点查找相关方法和属性 document/父节点.getElementById()document/父节 ...

  8. Django会话,用户和注册之用户认证

    通过session,我们可以在多次浏览器请求中保持数据, 接下来的部分就是用session来处理用户登录了. 当然,不能仅凭用户的一面之词,我们就相信,所以我们需要认证. 当然了,Django 也提供 ...

  9. JavaEE常用开发工具分享

    链接:https://pan.baidu.com/s/1Jxd2Y45LhWAUHc8-dM_ukw 提取码:h50f

  10. Object Detection: Face Detection using Haar Cascades

    目录   利用基于Haar特征的级联分类器实现人脸检测:官方教程 目标 学习基于Haar特征的级联分类器(Cascade Callifiers)实现人脸检测: 扩展到人眼检测: 基础知识 Paul V ...