当前位置

网站首页> 程序设计 > 开源项目 > 程序开发 > 浏览文章

[LintCode] Continuous Subarray Sum - Road to Glory

作者:小梦 来源: 网络 时间: 2024-02-09 阅读:

题目:Continuous Subarray Sum

Given an integer array, find a continuous subarray where the sum of numbers is the biggest. Your code should return the index of the first number and the index of the last number(If there are duplicate answers, return anyone).
Give [-3, 1, 3, -3, 4], return [1,4].

两点:

  1. 在res初始化时不放两个0进去,res的长度还是0,在for循环里会出问题。

  2. 循环里先判断上一次的结果,再执行sum+=A[i],减少不必要的分支语句。

public class Solution {    public ArrayList<Integer> continuousSubarraySum(int[] A) {        // Write your code here        ArrayList<Integer> res = new ArrayList<Integer>();        if (A == null || A.length == 0) {return res;        }        int sum = A[0];        int max = sum;        int start = 0, end = 0;        res.add(0);         res.add(0);        for (int i = 0; i < A.length; i++) {if (sum > max) {    res.set(0, start);     res.set(1, i-1); //here the index comes from last loop, so is (i-1)    max = sum;}if (sum < 0) {    start = i;    end = i;    sum = 0;}sum += A[i];        }        if (sum > max) {res.set(0, start);res.set(1, A.length-1);        }        return res;    }}

热点阅读

网友最爱