Possible Duplicate:
Is it possible to find two numbers whose difference is minimum in O(n) time
For example, in [4, 2, 7, 11, 8]
, the algorithm should return abs(7-8) = 1
.
The brute force way will be O(n2) and sorting will give O(nlogn). Is there more efficient way?
Thanks
sort((a,b) => { return a-b; }); let min = arr[1]-arr[0]; let n = arr. length; for (var i=0;i<n;i++) { let m = arr[i+1] - arr[i]; if(m < min){ m = min; } } return m; // minimum difference. } Show activity on this post. The given problem can easily be solved in O(n) time.
Subtract the smallest number from the largest number in the pair, this will generate the interval. Store in a variable the difference generated by every operation and update it only if the result is lower than the previous one, once it ends, the variable will store the smallest interval, which in this case is 2.
Overview. An array is a data structure consisting of a collection of elements (values or variables), each identified by at least one array index or key. Depending on the language, array types may overlap (or be identified with) other data types that describe aggregates of values, such as lists and strings.
I think sorting and comparing is going to be your best bet. Something like:
function minDiff( arr ) {
var min,
temp,
initDiff = false,
arr = arr.sort( function(a, b){return a-b} ),
last = arr.length - 1,
i;
for ( i = 0; i < last; i++ ) {
if ( !initDiff ) {
min = arr[i + 1] - arr[i];
initDiff = true;
} else {
temp = arr[i + 1] - arr[i];
if ( temp < min ) {
min = temp;
}
}
}
return min;
}
var myArr = [ 1, 8, 5, 96, 20, 47 ],
min = minDiff( myArr );
console.log( min ); // 3
A similar question here - Is it possible to find two numbers whose difference is minimum in O(n) time . It appears to be O(nlogn).
This page may give useful background info too.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With