我想知道是否有任何方法可以找出排序陣列中有多少對最簡單的方法是使用兩個 for 回圈
for (int i = 0; i < arr.length; i ) {
for (int j = i 1; j < arr.length; j ) {
if (arr[i] == arr[j])
但關鍵是這兩個 for 回圈即使在未排序的陣列中也能作業,如果我們的陣列已排序,有沒有辦法找到只有一個 for 或 while 回圈的對?例如可以是 {1, 1, 1, 2, 3, 3} 它有 4 對 [0][1], [0][2], [1][2], [4][5]
uj5u.com熱心網友回復:
嘗試這個。
static int combination(int start, int end) {
int size = end - start;
return size * (size - 1) / 2;
}
static int countDuplicatedNumberPairs(int[] arr) {
int length = arr.length, count = 0;
if (length <= 0) return count;
int start = 0, previous = arr[0];
for (int i = 1; i < length; i)
if (arr[i] != previous) {
count = combination(start, i);
start = i;
previous = arr[i];
}
count = combination(start, length);
return count;
}
public static void main(String[] args) {
int[] arr = {1, 1, 1, 2, 3, 3} ;
System.out.println(countDuplicatedNumberPairs(arr));
}
輸出:
4
uj5u.com熱心網友回復:
好吧,您不必將每個元素與其他元素進行比較(2 個嵌套的 for 回圈所做的),而只需將相鄰元素進行比較...
int paires = 0;
for(int i = 0; i < arr.lenght - 1; i ) {
if(arr[i] == arr[i 1]) paires ; // Test if the i-th element is equal to the i 1-th element and increasing counter if so.
}
注意for回圈只運行到n-1個元素,否則會出現空指標例外
uj5u.com熱心網友回復:
好吧,您需要遍歷陣列并計算連續的相同數字。如果遇到不同的數字,則需要計算最后看到的數字的對數。對于每個不同的數字,您都需要這樣做。
在下圖中,您會看到三個相同數字的子序列。
a b c
┌──┴──┐ ┌┴─┐ │
│ │ │ │ │
[ 1, 1, 1, 2, 2, 3 ]
讓我們首先定義一個方法來計算特定計數的對數。它的公式總是
????????2 ? ??
??(??)?=?─────
?????????2
int countPairs(int number) {
return number * (number - 1) / 2;
}
然后讓我們撰寫遍歷陣列的方法。我在代碼中添加了注釋來解釋會發生什么:
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;
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/368688.html
上一篇:我怎樣才能列印列的總和?
