有一個已經排序的數組(升序),數組中可能有正數、負數或0,求數組中元素的絕對值最小的數,要求,不能用順序比較的方法(復雜度需要小于O(n)),可以使用任何語言實現
例如,數組{-20,-13,-4, 6, 77,200} ,絕對值最小的是-4。
算法實現的基本思路
找到負數和正數的分界點,如果正好是0就是它了,如果是正數,再和左面相鄰的負數絕對值比較,如果是負數,取取絕對值與右面正數比較。還要考慮數組只有正數或負數的情況。
我根據這個思路用Java簡單實現了一個算法。大家有更好的實現方法歡迎跟帖
public class MinAbsoluteValue
{
private static int getMinAbsoluteValue(int[] source)
{
int index = 0;
int result = 0;
int startIndex = 0;
int endIndex = source.length - 1;
// 計算負數和正數分界點
while(true)
{ // 計算當前的索引
index = startIndex + (endIndex - startIndex) / 2;
result = source[index];<br> // 如果等于0,就直接返回了,0肯定是絕對值最小的
if(result==0)
{
return 0;
} // 如果值大于0,處理當前位置左側區域,因為負數肯定在左側
else if(result > 0)
{
if(index == 0)
{
break;
}
if(source[index-1] >0)
endIndex = index - 1;
else if(source[index-1] ==0)
return 0;
else
break;
} // 如果小于0,處理當前位置右側的區域,因為正數肯定在右側的位置
else
{
if(index == endIndex)
break;
if(source[index + 1] < 0)
startIndex = index + 1;
else if(source[index + 1] == 0)
return 0;
else
break;
}
}
// 根據分界點計算絕對值最小的數
if(source[index] > 0)
{
if(index == 0 || source[index] < Math.abs(source[index-1]))
result= source[index];
else
result = source[index-1];
}
else
{
if(index == source.length - 1 || Math.abs(source[index]) < source[index+1])
result= source[index];
else
result = source[index+1];
}
return result;
}
public static void main(String[] args) throws Exception
{
int[] arr1 = new int[]{-23,-22,-3,-2,1,2,3,5,20,120};
int[] arr2 = new int[]{-23,-22,-12,-6,-4};
int[] arr3 = new int[]{1,22,33,55,66,333};
int value = getMinAbsoluteValue(arr1);
System.out.println(value);
value = getMinAbsoluteValue(arr2);
System.out.println(value);
value = getMinAbsoluteValue(arr3);
System.out.println(value);
}
}
新浪微博:http://t.sina.com.cn/androidguy 昵稱:李寧_Lining