0:00

Consider the following data field and incomplete method, partialSum, which is intended to return an integer array sum such that for all isum[i] is equal to arr[0] + arr[1] + ... + arr[i]. For instance, if arr contains the values {1, 4, 1, 3}, the array sum will contain the values {1, 5, 6, 9}. Which of the following is true about the two implementations of missing code on line 9 that are proposed?

private int[] arr;

public int[] partialSum() {
   int[] sum = new int[arr.length];

   for (int j = 0; j < sum.length; j++)
      sum[j] = 0;

   /* missing code */
   return sum;
}


Implementation 1

for (int j = 0; j < arr.length; j++)
    sum[j] = sum[j - 1] + arr[j];


Implementation 2

for (int j = 0; j < arr.length; j++)
   for (int k = 0; k <= j; k++)
      sum[j] = sum [j] + arr[k];
j = 0时,sum[j - 1]不合法。
4


陈 欣

AADPS创始人

发表评论