s******n 发帖数: 57 | 1 Question:
Give an array like [-128, -35, -13, 0, 12, 67, 98], find two element which
the sum is
closest to 0.
solution:
http://www.careertea.com/techforum/post.aspx?PostID=5095 | f*********i 发帖数: 197 | 2 The solution costs O(nlogn) for sorting
However, since this array is already sorted, there is an O(N) approach
public static int array_sortedArray_find_close_to_zero(int[] arr){
int first=0,last = arr.length-1;
int sum = arr[first]+arr[last];
int min_to_0 = Math.abs(sum);
while(first
sum = arr[first]+arr[last];
if(Math.abs(sum)
min_to_0 = Math.abs(sum);
if(sum>0)
last--;
else if(sum<0)
first++;
else
return 0;
}
return min_to_0;
} |
|