Advertisement
DPELED

minAbsNum

Feb 21st, 2017
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.98 KB | None | 0 0
  1. public static int minAbsNum(int[] a)
  2.     {
  3.         if(a[0] >= 0)
  4.             return a[0] + a[1];
  5.         if(a[a.length - 1] <= 0)
  6.             return Math.abs(a[a.length - 1]) + Math.abs(a[a.length - 2]);
  7.         int high = a.length - 1;
  8.         int low = 0;
  9.         int mid = 0;
  10.         boolean found = false;
  11.         while(low <= high && !found){
  12.             mid = (low + high)/2;
  13.             if(a[mid] < 0)
  14.                 low = mid + 1;
  15.             else if(a[mid - 1] < 0)
  16.                 found = true;
  17.             else
  18.                 high = mid - 1;
  19.         }
  20.         if(Math.abs(a[mid - 1]) < Math.abs(a[mid]))
  21.             mid--;
  22.         if(mid == 0)
  23.             return Math.abs(a[mid]) + Math.abs(a[mid + 1]);
  24.         if(mid == a.length - 1)
  25.             return Math.abs(a[mid]) + Math.abs(a[mid - 1]);
  26.         int sum1 = Math.abs(a[mid]) + Math.abs(a[mid - 1]);
  27.         int sum2 = Math.abs(a[mid]) + Math.abs(a[mid + 1]);
  28.         return Math.min(sum1, sum2);
  29.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement