[LintCode] Closest Number in Sorted Array

Given a target number and an integer array A sorted in ascending order, find the index i in A such that A[i] is closest to the given target.

Return -1 if there is no element in the array.

 Notice

There can be duplicate elements in the array, and we can return any of the indices with same value.

Example

Given [1, 2, 3] and target = 2, return 1.

Given [1, 4, 6] and target = 3, return 1.

Given [1, 4, 6] and target = 5, return 1 or 2.

Given [1, 3, 3, 4] and target = 2, return 0 or 1 or 2.

Challenge 

O(logn) time complexity.

 

 1 public class Solution {
 2     /*
 3      * @param A: an integer array sorted in ascending order
 4      * @param target: An integer
 5      * @return: an integer
 6      */
 7     public int closestNumber(int[] A, int target) {
 8         if(A == null || A.length == 0) {
 9             return -1;
10         }
11         int low = 0, high = A.length - 1;
12         while(low + 1 < high) {
13             int mid = low + (high - low) / 2;
14             if(A[mid] == target) {
15                 return mid;
16             }
17             //numbers after index mid are >= A[mid] > target, which means they can't be closer to
18             //the target value than A[mid] is, so we can safely get rid of the bigger half.
19             else if(A[mid] > target) {
20                 high = mid;
21             }
22             //numbers before index mid are <= A[mid] < target, which means they can't be closer to
23             //the target value than A[mid] is, so we can safely get rid of the smaller half.
24             else {
25                 low = mid;
26             }
27         }
28         if(Math.abs(A[low] - target) <= Math.abs(A[high] - target)) {
29             return low;
30         }
31         return high;
32     }
33 }

 

 

Related Problems

K Closest Numbers in Sorted Array

Last Position of Target

Classical Binary Search

First Position of Target

 

posted @ 2017-11-13 02:29  Review->Improve  阅读(593)  评论(0编辑  收藏  举报