【问题标题】:Cumulative sum of an Array一个数组的累计和
【发布时间】:2014-08-11 16:57:54
【问题描述】:

所以我正在研究一个专注于获取数组的累积和的问题,例如,如果我有一个 ({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];
    }
    return total;
}

【问题讨论】:

  • 您永远不会阅读in 的任何元素。这似乎有问题。
  • 这甚至不会编译。你说你要返回一个int[],但你返回的是一个int
  • 对不起,我在我的主要方法中使用设置数组调用它..
  • 您的代码中有几个基本错误。 1) 您正在创建 out 作为大小为 1 的数组。 2)您的方法 sig 说您返回一个 int[] 但实际上您返回的是一个 int。 3) 你从来没有真正读取过输入数组中的任何值。

标签: java arrays loops for-loop


【解决方案1】:

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

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;
}

【讨论】:

    【解决方案2】:
    public class Sum {
        public static void main(String[] args) {
            int in[] = {1,2,3,4,5,6,7,8,9};
            int[] out = new int[in.length];
            out[0] = in[0];
            for (int i = 1; i < out.length; i++) 
                out[i] = out[i-1] + in[i];
    
            for (int i = 0; i < out.length; i++) 
                System.out.print(out[i]+" ");
        }
    }
    

    输出

    1 3 6 10 15 21 28 36 45 
    

    如果你想把它放在一个方法中,你可以像这样返回最后一个元素:

    return out[out.length-1];
    

    【讨论】:

      【解决方案3】:
      public static int[] makeCumul(int[] in) {
          int[] out = new int[in.length];
          int sum = 0;
          for(int i = 0; i < in.length; i++){
              sum += in[i];
              out[i] = sum;
          }
          return out;
      }
      

      我相信这就是您正在寻找的。保留一个累积总和,并使用每个元素更新该总和。更新总和后,将元素替换为总和。

      当你创建一个新数组时,使用它来初始化它

      int[] out = new int[ARRAY SIZE HERE];
      

      您还应该注意,在方法签名中,您将返回一个整数数组,而变量total 是一个整数,而不是整数数组。所以你想返回变量out

      给我输出:

      0
      2
      5
      4
      3
      

      【讨论】:

        猜你喜欢
        • 2018-03-02
        • 2019-05-14
        • 1970-01-01
        • 1970-01-01
        • 2014-01-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多