LintCode Subarray Sum

来源:互联网 发布:linux开机运行程序 编辑:程序博客网 时间:2024/05/21 23:01

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

Notice

There is at least one subarray that it’s sum equals to zero.

Have you met this question in a real interview? Yes
Example
Given [-3, 1, 2, -3, 4], return [0, 2] or [1, 3].

题目非常简单

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        if (nums == null || nums.length == 0) {            return null;        }        ArrayList<Integer> list = new ArrayList<>();        Map<Integer, Integer> map = new HashMap<>();        map.put(0, 0);        int sum = 0;        for (int i = 0; i < nums.length; i++) {            sum += nums[i];            if (map.containsKey(sum)) {                if (sum == 0) {                    list.add(map.get(sum));                    list.add(i);                } else {                    list.add(map.get(sum) + 1);                    list.add(i);                }                break;            } else {                map.put(sum, i);            }        }        return list;    }}
0 0