您的位置:首页 > 编程语言 > Go语言

Google在Codility.com上的一个测试范例

2011-02-23 10:10 316 查看
Task description

Equilibrium index of a sequence is an index such that the sum of elements at lower indexes is equal to the sum of elements at higher indexes. For example, in a sequence A:

A[0]=-7 A[1]=1 A[2]=5 A[3]=2 A[4]=-4 A[5]=3 A[6]=0

3 is an equilibrium index, because:

A[0]+A[1]+A[2]=A[4]+A[5]+A[6]

6 is also an equilibrium index, because:

A[0]+A[1]+A[2]+A[3]+A[4]+A[5]=0

(sum of zero elements is zero) 7 is not an equilibrium index, because it is not a valid index of sequence A.

If you still have doubts, this is a precise definition: the integer k is an equilibrium index of a sequence

if and only if

and

.

Assume the sum of zero elements is equal zero. Write a function

int equi(int[] A);

that given a sequence, returns its equilibrium index (any) or -1 if no equilibrium indexes exist. Assume that the sequence may be very long.

Copyright 2009-2010 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.
Solution
int equi ( const vector<int> &A ) {
// write your code here
long long sum = 0;
int len = A.size();
for(int i=0; i<len; ++i)
{
sum += A[i];
}
if(len == 0)
return -1;
if(len == 1)
return 0;

long long lsum=0, rsum = sum;

for(int i=0; i<len; ++i)
{
rsum -= A[i];
if(rsum == lsum)
return i;
lsum += A[i];
}
return -1;
}

Analysis


Detected time complexity:
[b]O(n)

testtimeresult
example
Test from the task description
0.001 s.OK
extreme_empty
Empty array
0.004 s.OK
extreme_first0.004 s.OK
extreme_large_numbers
Sequence with extremly large numbers testing arithmetic overflow.
0.004 s.OK
extreme_last0.004 s.OK
extreme_single_zero0.004 s.OK
extreme_sum_0
sequence with sum=0
0.001 s.OK
simple0.001 s.OK
single_non_zero0.004 s.OK
combinations_of_two
multiple runs, all combinations of {-1,0,1}^2
0.001 s.OK
combinations_of_three
multiple runs, all combinations of {-1,0,1}^3
0.001 s.OK
small_pyramid0.004 s.OK
large_long_sequence_of_ones0.008 s.OK
large_long_sequence_of_minus_ones0.020 s.OK
medium_pyramid0.004 s.OK
large_pyramid
Large performance test, O(n^2) solutions should fail.
0.052 s.OK
[/b]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐