我有一個很長很長陣列和我得2個元素的所有可能組合的最小差異的所有可能的元件的組合的最小的差。獲取陣列
這是我的代碼:
[...]
int diff = 1000000; // a very big difference that i'm sure is too big
int tmpDiff; // swap
//Compare
for (size_t i = 0; i < N; i++) { // I try every combination of 2 elements of array
for (size_t j = i + 1; j < N; j++) { // don't repeat same elements
tmpDiff = abs(array[i] - array[j]); // get the difference
if (diff > tmpDiff) { // if it is smaller is the difference i need
diff = tmpDiff;
}
}
}
[...]
它需要太多的時間。我們如何優化表演?
使用高效排序,然後依次比較相鄰元素。 – dbush