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

[LintCode] 459 Closest Number in Sorted Array

时间:2017-04-24 09:57:07      阅读:105      评论:0      收藏:0      [点我收藏+]

标签:start   div   tco   格式   get   ber   否则   not   范围   

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 }    

 

[LintCode] 459 Closest Number in Sorted Array

标签:start   div   tco   格式   get   ber   否则   not   范围   

原文地址:http://www.cnblogs.com/panini/p/6755040.html

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