Subarray Sum
2015-11-29 15:09
363 查看
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].
Note
There is at least one subarray that it’s sum equals to zero.
有一个O(N)的解法。使用Map 来记录index, sum的值。当遇到两个index的sum相同时,表示从index1+1到index2是一个解。
注意:添加一个index = -1作为虚拟节点。这样我们才可以记录index1 = 0的解。
空间复杂度:O(N)
Example
Given [-3, 1, 2, -3, 4], return [0, 2] or [1, 3].
Note
There is at least one subarray that it’s sum equals to zero.
有一个O(N)的解法。使用Map 来记录index, sum的值。当遇到两个index的sum相同时,表示从index1+1到index2是一个解。
注意:添加一个index = -1作为虚拟节点。这样我们才可以记录index1 = 0的解。
空间复杂度:O(N)
public class Solution { /** * @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 */ public ArrayList<Integer> subarraySum(int[] nums) { // write your code here int len = nums.length; ArrayList<Integer> ans = new ArrayList<Integer>(); HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); map.put(0, -1); int sum = 0; for (int i = 0; i < len; i++) { sum += nums[i]; if (map.containsKey(sum)) { ans.add(map.get(sum) + 1); ans.add(i); return ans; } map.put(sum, i); } return ans; } }
相关文章推荐
- LNMP搭建与环境配置
- Hive安装及使用攻略
- gnuradio调试方法
- Java日志学习六:各种日志系统间的桥接
- 手机号归属地查询
- cpu结构研究
- 大白书 1.1节 思维的体操
- Go 语言数组
- 《apue》读书笔记 第四章 文件和目录(1)
- Linux的tar命令使用
- iOS Multiview Applications
- Go 语言变量作用域
- 探索ListActivity
- http基础概念
- Oc KVC 键值编码
- MYSQL数据丢失讨论
- Centos7添加epel源并升级php
- 把含有&#x字符串的网页还原
- HDU 4525 威威猫系列故事 (模拟)
- innodb_flush_method理解