Java – check a data test – pair_ sum_ even_ count

As part of the recruitment process, I recently conducted an online test on data Within an hour, I was given two simple questions to solve For those who don't know the data, it is an online coding test website. You can solve ACM style problems in many different languages

If you have more than 30 minutes, check this http://codility.com/demo/run/

My weapon of choice is usually Java

So I have a question as follows (I will try to remember that screenshots should be taken)

Let's say you have an array a [0] = 1 a [1] = – 1 A [n] = x

So when a [i] a [J] even where will I find the smartest way? Ĵ

So if we have {1,2,3,4,5} we have 1,3,5,2,4,5 = 4 pairs that are uniform

The code I write is something

int sum=0;
for(int i=0;i<A.length-1;i++){
 for (int j=i+1;j<A.length;j++){
   if( ((A[i]+A[j])%2) == 0 && i<j) {
       sum++;
    }
  }
}

There is also a limit. If the logarithm is greater than 1e9, it should run - 1 again, but let it forget it

Can you suggest a better solution? Normally, the number of elements does not exceed 1e9

I think the above code deducted 27 points (i.e. imperfect) Programmability gives a detailed evaluation of errors, and I don't have such permission now

Solution

The sum of two integers, even if and only if they are both even and odd You can simply pass through the array and count and average and odds The number of possibilities to combine K numbers from a set of size n is n/ ((N-k)!· k!). You only need to take the quantity / times as N and 2 as K. for this purpose, the above is simplified as (n · (n-1)) / 2 All conditions I < J specify that each combination is calculated only once

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>