数组的累积和 [英] Cumulative sum of an Array

查看:135
本文介绍了数组的累积和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我正在研究一个问题,重点是采取一个数组的累加和,所以例如,如果我有({0,2,3,-1,-1})数组,它返回{0, 2,5,4,3} ...或者如果你有一个[1,2,3,4,5,6,7,8,9,10]的数组,它应该返回[1,3,6,10 ,15,21,28,36,45,55] ...

现在我正在努力解决两个问题,我必须使用给定的方法,而我因为总的来说,我不知道怎么回事。我的代码我知道它可以用来加总一个数组的总和而不是像我的例子中的累积总和。任何指导都会有帮助的。

  public int [] makeCumul(int [] in){
int [] out = {in.length};
int total = 0;
for(int i = 0; i< out.length; i ++){
total + = out [i];
}
总回报;


解决方案

部分,但也不更新out数组,而不是返回它。这应该适合你。

  public int [] makeCumul(int [] in){
int [] out = new int [in.length];
int total = 0;
for(int i = 0; i total + = in [i];
out [i] = total;
}
退货;
}


So i'm working on a problem that focuses on taking the cumulative sum of an array so for example if i have an array of ({0,2,3,-1,-1}) it returns {0,2,5,4,3}... or if you have an array of [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] it should return [1, 3, 6, 10, 15, 21, 28, 36, 45, 55]...

Right now i'm struggling with two problems one i have to use the method given and i'm struggling with what to return because total will not.. To my code i know it works for adding up the sum of an array but not the cumulative sum as in my examples.. any guidelines would be helpful.

public int[] makeCumul(int[] in) {
    int[] out = { in.length };
    int total = 0;
    for (int i = 0; i < out.length; i++) {
        total += out[i];
    }
    return total;
}

解决方案

Not reading the in array, partly, but also not updating the out array, and not returning it. This should work for you.

public int[] makeCumul(int[] in) {
    int[] out = new int[in.length];
    int total = 0;
    for (int i = 0; i < in.length; i++) {
        total += in[i];
        out[i] = total;
    }
    return out;
}

这篇关于数组的累积和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆