有一個升序排列的數組,數組中可能有正數,負數或0. 求數組中元素的絕對值最小的數. 例如 數組{-10, 05, 02 ,7,15,50} 絕對值最小的是-2c++
#include <bits/stdc++.h> using namespace std; void f(int a[], int len) { if (a[len-1] <= 0) { cout << abs(a[len-1]) <<endl; return ; } if (a[0] >= 0) { cout << a[0] << endl; return ; } // 有正有負 int l = 0, r = len-1; while (l <= r) { int m = (l + r) / 2; if(a[m] == 0) { cout << a[m] << endl; return ; } else if(a[m] > 0) { if(a[m-1] < 0) { int mn = min(abs(a[m-1]), a[m]); cout<< mn <<endl; return ; } else if (a[m-1] == 0) { cout << 0 <<endl; return ; } else { // a[m-1] > 0 r = m-1; } } else { // a[m] < 0 if(a[m+1] > 0) { int mn = min(abs(a[m]), a[m+1]); cout << mn <<endl; return ; } else if(a[m+1] == 0) { cout << 0 <<endl; return ; } else { // a[m+1] < 0 l = m+1; } } } return ; } int main() { int a1[] = {-10, -5, -2, 7, 15 ,50}; int a2[] = {2,4,6,8,27}; int a3[] = {-13, -9, -7, -3}; int l1 = 6, l2 = 5, l3 = 4; f(a1, l1); f(a2, l2); f(a3, l3); return 0; }