*[Lintcode] Subarray Sum
2016-04-16 17:09
211 查看
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
考虑特殊情况, 即只有0, 区间从0开始和区间从中间开始。
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) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
ArrayList<Integer> res = new ArrayList<Integer>();
map.put(0, -1);
int sum = 0;
for(int i = 0; i < nums.length; i++) {
sum += nums[i];
if(map.containsKey(sum)) {
res.add(i);
res.add(map.get(sum) + 1);
return res;
}
map.put(sum, i);
}
return res;
}
}
Example
Given
[-3, 1, 2, -3, 4],
return
[0, 2]or
[1, 3].
考虑特殊情况, 即只有0, 区间从0开始和区间从中间开始。
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) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
ArrayList<Integer> res = new ArrayList<Integer>();
map.put(0, -1);
int sum = 0;
for(int i = 0; i < nums.length; i++) {
sum += nums[i];
if(map.containsKey(sum)) {
res.add(i);
res.add(map.get(sum) + 1);
return res;
}
map.put(sum, i);
}
return res;
}
}
相关文章推荐
- LintCode Majority Number iii
- LintCode-最大数
- Subtree
- LintCode --number-of-airplanes-in-the-sky(数飞机)
- LintCode --invert-binary-tree(翻转二叉树)
- LintCode --find-the-missing-number(寻找缺失的数)
- LintCode--best-time-to-buy-and-sell-stock(买卖股票的最佳时机)
- LintCode--best-time-to-buy-and-sell-stock-ii(买卖股票的最佳时机 II)
- 中位数 21% 通过 给定一个未排序的整数数组,找到其中位数。 中位数是排序后数组的中间值,如果数组的个数是偶数个,则返回排序后数组的第N/2个数
- LintCode 翻转二叉树
- LintCode 寻找缺失的数
- LintCode 更新二进制位
- Lintcode 二叉树的后序遍历
- Lintcode 二叉树中序遍历
- Lintcode 二叉树前序遍历
- Lintcode 尾部零的个数
- Lintcode 比较字符串
- Lintcode 主元素
- LintCode 最小调整代价
- LintCode 木材加工