Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

2014-07-01代码游戏 - 简单DEMO #37

Open
frankbp opened this issue Jun 25, 2014 · 1 comment
Open

2014-07-01代码游戏 - 简单DEMO #37

frankbp opened this issue Jun 25, 2014 · 1 comment

Comments

@frankbp
Copy link

frankbp commented Jun 25, 2014

一个序列的平衡点是这样的,它的左边的所有的元素的和应该等于右边的所有的元素的和,比如在下面的序列A:
A[0] = -7 A[1] = 1 A[2] = 5
A[3] = 2 A[4] = -4 A[5] = 3
A[6] = 0
3是一个平衡点因为:
A[0] + A[1] + A[2] = A[4] + A[5] + A[6]
6也是一个平衡点因为:
A[0] + A[1] + A[2] + A[3] + A[4] + A[5] = 0
(零个元素的和是零) 索引7不是平衡点,因为它不是序列A的有效索引。
如果你仍然不是很清楚,那么这里给出了明确的定义:0 ≤ k < n 并且 sum[i=0]k-1 A[i] = sum[i=k+1]n-1 A[i]。时, 整数k是序列A[0], A[1], ..., A[n−1]$ 的平衡点,这里我们假定零个元素的和为零。
请写一个函数
int solution(int A[], int N);
返回给定序列的平衡点(任意一个)如果没有平衡点则返回−1,假设这个序列可达到非常大。
假定:
N 是 [0..100,000] 内的 整数;
数组 A 每个元素是取值范围 [−2,147,483,648..2,147,483,647] 内的 整数 .
复杂度:
最坏-情况下,期望的时间复杂度是 O(N);
最坏-情况下,期望的空间复杂度是 O(N), 输入存储除外 (不计输入参数所需的存储空间).
输入数组中的元素可以修改.

@frankbp frankbp changed the title 2014-07-01代码游戏 - 简单游戏DEMO 2014-07-01代码游戏 - 简单DEMO Jun 25, 2014
@gltianwen
Copy link

if (A.length == 0)
             return 0;
  long summary = Arrays.stream(A).Sum();

  long sum_left = 0;
  for (int i = 0; i < A.length; i++)
  {
       long sum_right = summary - sum_left - A[i];
       if (sum_left == sum_right)
       {
            return i;
        }
        sum_left += A[i];
   }
    return 0;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants