[LintCode] 459 Closest Number in Sorted Array

Description
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.

4/23/2017

算法班,直接套用解题格式

注意第16,17行把超越输入范围的也包含进去,否则最后一行需要用绝对值来判断。

 1 public int totalOccurance(int[] A, int target) {
 2     if (A == null || A.length == 0) return -1;
 3     int ret;
 4     int start = 0, end = A.length - 1;
 5 
 6     while (start + 1 < end) {
 7         int mid = start + (end - start) / 2;
 8         if (A[mid] == target) return mid;
 9         if (A[mid[ < target) {
10             end = mid;
11         } else {
12             start = mid;
13         }
14     }
15 
16     if (A[start] >= target) return start;
17     if (A[end] <= target) return end;
18     return Math.abs(A[end] - target) < Math.abs(target - A[start])? end: start;
19 }    
原文地址:https://www.cnblogs.com/panini/p/6755040.html