码迷,mamicode.com
首页 > 其他好文 > 详细

Closet Number in sorted array

时间:2016-01-19 10:28:02      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:

 

 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.

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.

Note

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

 1 class Solution {
 2 public:
 3     /**
 4      * @param A an integer array sorted in ascending order
 5      * @param target an integer
 6      * @return an integer
 7      */
 8     int closestNumber(vector<int>& A, int target) {
 9         if (A.size() == 0) {
10             return -1;
11         }
12         
13         int b = 0, e = A.size() - 1;
14         while (b + 1 < e) {
15             int mid = b + (e - b) / 2;
16             if (A[mid] == target) {
17                 return mid;
18             } else if (A[mid] < target) {
19                 b = mid;
20             } else {
21                 e = mid;
22             }
23         }
24         if (abs(A[b] - target) < abs(A[e] - target)) {
25             return b;
26         } else {
27             return e;
28         }
29     }
30 };

 

Closet Number in sorted array

标签:

原文地址:http://www.cnblogs.com/whlsai/p/5141308.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!