[LintCode] Subarray Sum & Subarray Sum II
2015-06-01 12:21
387 查看
Subarray Sum
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
[-3, 1, 2, -3, 4], return
[0, 2]or
[1, 3].
用hashmap来存从nums[0]到nums[i]的和以及当前下标i,遍历数组求前缀和acc[i],如果发现acc[i]的值已经在hashmap中的,那么说明已经找到一段子数组和为0了。
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){ // write your code here map<int, int> has; int sum = 0; has[0] = -1; vector<int> res; for (int i = 0; i < nums.size(); ++i) { sum += nums[i]; if (has.find(sum) != has.end()) { res.push_back(has[sum] + 1); res.push_back(i); return res; } else { has[sum] = i; } } return res; } };
Subarray Sum II
Given an integer array, find a subarray where the sum of numbers is between two given interval. Your code should return the number of possible answer.Example
Given
[1,2,3,4]and interval =
[1,3], return
4. The possible answers are:
[0, 0] [0, 1] [1, 1] [3, 3]
先求出前缀和,然后枚举求两个前缀和的差。如果差在start与end之间,就给res+1。注意前缀和数组前要插入一个0。
class Solution { public: /** * @param A an integer array * @param start an integer * @param end an integer * @return the number of possible answer */ int subarraySumII(vector<int>& A, int start, int end) { // Write your code here vector<int> acc(A); acc.insert(acc.begin(), 0); for (int i = 1; i < acc.size(); ++i) { acc[i] += acc[i-1]; } int tmp, res = 0; for (int i = 0; i < acc.size() - 1; ++i) { for (int j = i + 1; j < acc.size(); ++j) { tmp = acc[j] - acc[i]; if (tmp>= start && tmp <= end) ++res; } } return res; } };
相关文章推荐
- Spring <context:annotation-config/> 说明
- javascript基础,如何理解对象
- 哪里有药Q21205507
- Python快速入门(2)
- 字符字节
- Web前端开发推荐阅读书籍-精华
- java项目出现红色感叹号
- MyEclipse如何调字体的大小
- pandoc格式转换示例
- linux tar.gz zip 解压缩 压缩命令
- 从百度hi搬过来
- jQuery插件—validate
- 《Hadoop基础教程》之初识Hadoop
- PHP explode() 函数
- UML 结构图之类图 总结
- var object dynamic的区别
- JS实现兼容各浏览器解析XML文档数据的方法
- 【Linux】linux经常使用基本命令
- PHP microtime() 函数
- VIM 安装taglist