给出零索引数组和该数组的平衡指数

Sir*_*que 4 c++ java arrays algorithm data-structures

给出了由N个整数组成的零索引数组A. 该数组的平衡指数是任何整数P,使得0≤P<N且较低指数的元素之和等于较高指数的元素之和,即A [0] + A [1] + ...... + A [P-1] = A [P + 1] + ... + A [N-2] + A [N-1].假设零元素的总和等于0.如果P = 0或P = N-1,则可能发生这种情况.

例如,考虑以下由N = 8个元素组成的数组A:

  A[0] = -1
  A[1] =  3
  A[2] = -4
  A[3] =  5
  A[4] =  1
  A[5] = -6
  A[6] =  2
  A[7] =  1
Run Code Online (Sandbox Code Playgroud)

P = 1是该阵列的平衡指数,因为:

A[0] = ?1 = A[2] + A[3] + A[4] + A[5] + A[6] + A[7]
Run Code Online (Sandbox Code Playgroud)

P = 3是该阵列的平衡指数,因为:

A[0] + A[1] + A[2] = ?2 = A[4] + A[5] + A[6] + A[7]
Run Code Online (Sandbox Code Playgroud)

P = 7也是一个均衡指数,因为:

A[0] + A[1] + A[2] + A[3] + A[4] + A[5] + A[6] = 0
Run Code Online (Sandbox Code Playgroud)

并且没有索引大于7的元素.

P = 8不是平衡指数,因为它不满足0≤P<N的条件.

现在我必须写一个函数:

int solution(int A[], int N);
Run Code Online (Sandbox Code Playgroud)

在给定由N个整数组成的零索引数组A的情况下,返回其任何均衡指数.如果不存在均衡指数,则该函数应返回-1.

例如,给定如上所示的阵列A,该函数可以返回1,3或7,如上所述.

假使,假设:

N is an integer within the range [0..100,000];
each element of array A is an integer within the range [?2,147,483,648..2,147,483,647].
Run Code Online (Sandbox Code Playgroud)

这里有一些复杂性:

Elements of input arrays can be modified.
Run Code Online (Sandbox Code Playgroud)

Bas*_*hir 6

用c#100%得分

using System;
class Solution {
    public int solution(int[] A) {
        // First calculate sum of complete array as `sum_right`
        long sum_right = 0;
        for (int i = 0; i < A.Length; i++)
        {
            sum_right += A[i];
        }

        // start calculating sum from left side (lower index) as `sum_left`
        // in each iteration subtract A[i] from complete array sum - `sum_right`
        long sum_left = 0;
        for (int p = 0; p < A.Length; p++)
        {
            sum_left += p - 1 < 0 ? 0: A[p-1];
            sum_right -= A[p];
            if (sum_left == sum_right)
            {
                 return p;
            }
        }
        return -1;


    }
}
Run Code Online (Sandbox Code Playgroud)

  • 一点点解释肯定会提高你答案的质量. (4认同)

Asi*_*chi 5

100% - Java

int solution(int A[], int N) {

    long sum = 0;
    for (int i = 0; i < A.length; i++) {
        sum += (long) A[i];
    }
    long leftSum = 0;
    long rightSum = 0;

    for (int i = 0; i < A.length; i++) {
        rightSum = sum - (leftSum + A[i]);
        if (leftSum == rightSum) {
            return i;
        }
        leftSum += A[i];
    }
    return -1;
}
Run Code Online (Sandbox Code Playgroud)

}