[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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值