[LintCode] 459 Closest Number in Sorted Array

Posted panini

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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 }    

 

以上是关于[LintCode] 459 Closest Number in Sorted Array的主要内容,如果未能解决你的问题,请参考以下文章

lintcode-medium-3 Sum Closest

lintcode-medium-Subarray Sum Closest

K Closest Points Lintcode

lintcode900 - Closest Binary Search Tree Value - easy

LeetCode 3Sum Closest

5 - Binary Tree & Tree-based DFS