Java初学者在数组中推进总和

时间:2017-01-10 10:28:40

标签: java prefix

我的程序应该采用提供的数组并创建一个新数组,其中每个元素是原始数组中前面元素的总和。例如,新数组中的元素1是原始数组中的元素1。新数组中的元素二是原始数组中元素一和元素二的和。新数组中的元素3是原始数组中元素1,2和3的总和。我写了这个,但我知道它不完整。请指导。

public class PrefixSum
    {
    public static void main(String[] args)
    {
        int[] array = new int[]{0,5,1,-3,2,0,4};
        int[] newArray = new int[7];
        int x = 0;
        for(int i = 0; i < array.length; i++)
        {
            x = array[i];      
            x = x + i;
        }
        newArray[0] = 0;
        System.out.println(" " + newArray[x]);
    }
}

4 个答案:

答案 0 :(得分:4)

您可以使用变量runningTotal来计算运行总数,如下所示:

import java.util.Arrays;

class Main {
  public static void main(String[] args) {
    int[] originalArray = new int[]{0,5,1,-3,2,0,4};
    int[] sumArray = new int[originalArray.length];

    int runningTotal = 0;
    for(int i = 0; i < originalArray.length; i++){
      runningTotal += originalArray[i];
      sumArray[i] = runningTotal;
    }

    System.out.println("The originalArray is: " + Arrays.toString(originalArray));
    System.out.println("The sumArray is: " + Arrays.toString(sumArray));
  }
}

<强>输出:

The originalArray is: [0, 5, 1, -3, 2, 0, 4]
The sumArray is: [0, 5, 6, 3, 5, 5, 9]

试试here!

答案 1 :(得分:2)

您可以Debug此代码以了解更改。

public static void main(String[] args)
{
    int[] array = new int[]{0,5,1,-3,2,0,4};
    int[] newArray = new int[7];
    int x = 0;
    for(int i = 0; i < array.length; i++)
    {
        x += array[i];      
        newArray[i] = x;
    }
}

答案 2 :(得分:1)

public static void main(String[] args)
{
    int[] array = new int[]{0,5,1,-3,2,0,4};
    int[] newArray = new int[7];
    int sum = 0;
    for(int i = 0; i < array.length; i++)
    {
        sum += array[i];     
        newArray[i]= sum;
        System.out.println(" " +newArray[i]);
    }

}

答案 3 :(得分:1)

List<Integer> sums = new ArrayList<>();
Stream.of(0, 5, 1, -3, 2, 0, 4).reduce((left, right) -> {
    sums.add(left + right);
    return left + right;
});

运行产量后打印sums

[0, 5, 6, 3, 5, 5, 9]

试试here