好吧,您需要遍历数组并计算连续相同的数字。如果遇到不同的数字,则需要计算最后看到的数字的对数。对于每个不同的数字,您都需要这样做。
在下图中,您可以看到三个相同数字的子序列。
a b c
┌──┴──┐ ┌┴─┐ │
│ │ │ │ │
[ 1, 1, 1, 2, 2, 3 ]
让我们首先定义一种方法来计算特定计数的对数。它的公式总是
⠀⠀⠀⠀⠀⠀?² − ?
?(?)⠀=⠀──────
⠀⠀⠀⠀⠀⠀⠀⠀2
int countPairs(int number) {
return number * (number - 1) / 2;
}
然后让我们编写遍历数组的方法。我在代码中添加了 cmets 来解释发生了什么:
int countPairs(int[] array) {
// If our array is empty or contains a single element, then there are no
// pairs, obviously
if (array.length < 2) {
return 0;
}
// We keep track of the total number of pairs here
int totalPairs = 0;
// We also keep track of the number of consecutive identical numbers.
int consecutive = 1;
// We begin our index with 1, since we need to compare it to the previous one
// (and we don't want an ArrayIndexOutOfBoundsException to be thrown)
for (int i = 1; i < array.length; i++) {
if (array[i] == array[i - 1]) {
// If the encountered number is the same as the previous one,
// then increment the subsequence counter
consecutive++;
}
else {
// If the number is different than the previous one, then a new subsequence
// has started. We need to process the previous subsequence. Calculate the
// number of pairs, add it to the result, and then reset `consecutive`
totalPairs += countPairs(consecutive);
consecutive = 1;
}
}
// At last, process the last sequence
totalPairs += countPairs(consecutive);
return totalPairs;