Java 有人解释这是怎么回事吗?

Java 有人解释这是怎么回事吗?,java,Java,任何人,请解释下面的程序如何返回正确的配对 /** * Write a function that, given an array A consisting of N integers, returns the * number of pairs (P, Q) such that 0 ≤ P < Q < N and (A[P] + A[Q]) is even. * * The function should return −1 if the number of such pa

任何人,请解释下面的程序如何返回正确的配对

/**
 * Write a function that, given an array A consisting of N integers, returns the
 * number of pairs (P, Q) such that 0 ≤ P < Q < N and (A[P] + A[Q]) is even.
 *
 * The function should return −1 if the number of such pairs exceeds
 * 1,000,000,000.
 *
 * For example, given array A such that: A[0] = 2, A[1] = 1, A[2] = 5, A[3] =
 * −6, A[4] = 9.
 *
 * The function should return 4, because there are four pairs that fulfill the
 * above condition, namely (0,3), (1,2), (1,4), (2,4). Assume that: N is an
 * integer within the range [0..1,000,000]; each element of array A is an
 * integer within the range [−2,147,483,648..2,147,483,647].
 */



public class NumEvenSumPairs {
    public static int numEvenSumPairs(int[] numbers) {
        int evenCount = 0;
        int oddCount = 0;

        for (int number : numbers) {
            if ((number & 1) == 0) {
                evenCount++;
            }
        }

        oddCount = numbers.length - evenCount;


        long temp = (evenCount * (evenCount - 1) / 2)
                + (oddCount * (oddCount - 1) / 2);  // doubt on this line.

        if (temp >= 1000000000) {
            return -1;
        }

        return (int) temp;
    }
}

该代码计算数组中的偶数evenCount和奇数oddCount

每两个偶数组成一对,其和为偶数。这类对的数量为evenCount*evenCount-1/2。有evenCount方法选择第一个偶数,evenCount-1选择第二个,显然a,b与b,a是同一对,因此除以2

奇数也是如此。每两个奇数组成一对,其和为偶数


这就是你的get temp=evenCount*evenCount-1/2+oddCount*oddCount-1/2的方式。

与其向我解释这是如何工作的,这是非常广泛的,也许你应该解释到底是什么让你困惑,也许有人能够回答它。关于temp变量的设置值。