LintCode - 子数组之和(普通)

版权声明:本文为博主原创文章,未经博主允许不得转载。

难度:容易
要求:

给定一个整数数组,找到和为零的子数组。你的代码应该返回满足要求的子数组的起始位置和结束位置

样例

给出 [-3, 1, 2, -3, 4],返回[0, 2] 或者 [1, 3].

思路

    /**
     * @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) {
        int start = 0;
        int end = 0;
        int sum = 0;
        labe:for(int i = 0; i < nums.length; i++){
            sum = 0;
            start = i;
            for(int j = i; j < nums.length; j++){
                sum += nums[j];
                if(sum == 0){
                    end = j;
                    break labe;
                }
            }
        }
        
        ArrayList<Integer> list = new ArrayList<Integer>();
        list.add(start);
        list.add(end);
        return list;
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容