磁带平衡Codility培训磁带、Codility

2023-09-10 23:55:18 作者:烟酒伤肺伤胃不伤心

我收到了codility测试一天的工作,因此我一直在使用的一些问题,从他们的训练页练习 链接

I received a codility test the other day for a job, as such I've been practicing using some of the problems from their training page Link

不幸的是,我只能够得到83/100上的磁带 - 均衡的问题。

Unfortunately, I've only been able to get 83/100 on the Tape-Equilibrium question.

其内容如下:

A non-empty zero-indexed array A consisting of N integers is given. Array A represents     numbers on a tape.

Any integer P, such that 0 < P < N, splits this tape into two non−empty parts: A[0], A[1], ..., A[P − 1] and A[P], A[P + 1], ..., A[N − 1].

The difference between the two parts is the value of: |(A[0] + A[1] + ... + A[P − 1]) − (A[P] + A[P + 1] + ... + A[N − 1])|

In other words, it is the **absolute** difference between the sum of the first part and the sum of the second part.

写一个函数,考虑N个整数的非空零索引数组A,返回可以达到的最小差异。

Write a function that, given a non-empty zero-indexed array A of N integers, returns the minimal difference that can be achieved.

例如:

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

我们可以在四个地方分割该磁带:

We can split this tape in four places:

P = 1,差值= | 3 - 10 | = 7 P = 2,差= | 4 - 9 | = 5 P = 3,差值= | 6 - 7 | = 1 P = 4,差= | 10 - 3 | = 7

在这种情况下,我将返回1,因为它是最小的区别。

In this case I would return 1 as it is the smallest difference.

N是一个int,范围[2..100,000] A的每个元素是int,范围[-1,000..1,000。它需要O(n)的时间复杂度,

N is an int, range [2..100,000]; each element of A is an int, range [−1,000..1,000]. It needs to be O(n) time complexity,

我的code是如下:

import java.math.*;
class Solution {
public int solution(int[] A) {

    long sumright = 0;
    long sumleft = 0;
    long ans;

    for (int i =1;i<A.length;i++)
    {
        sumright += A[i];
    }

    sumleft = A[0];
    ans =Math.abs(Math.abs(sumright)+Math.abs(sumleft));

    for (int P=1; P<A.length; P++)
    {
        if (Math.abs(Math.abs(sumleft) - Math.abs(sumright))<ans)
        {
            ans = Math.abs(Math.abs(sumleft) - Math.abs(sumright));
        }
        sumleft += A[P];
        sumright -=A[P];
    }
    return (int) ans;  
}

我就有点疯狂的Math.abs。它无法在这两个试验区的双冠王(我认为这是两个值,-1000和1000,和小。 http://codility.com/demo/results/demo9DAQ4T-2HS/

I went a bit mad with the Math.abs. The two test areas it fails on are "double" (which I think is two values, -1000 and 1000, and "small". http://codility.com/demo/results/demo9DAQ4T-2HS/

任何帮助将是AP preciated,我要确保我没有做任何基本的错误。

Any help would be appreciated, I want to make sure I'm not making any basic mistakes.

推荐答案

您的解决方案已经是O(N)。你需要从sumleft和sumright去除腹部。

Your solution is already O(N). You need to remove the abs from sumleft and sumright.

if (Math.abs( sumleft - sumright ) < ans)
{
  ans = Math.abs( sumleft - sumright );
}

另外前第二个循环,

Also before the second for loop,

ans =Math.abs( sumleft - sumright );

这应该工作。

It should work.