标签:and mon text sel oat contain find [] out
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | public class Solution { /** * @param A an integer array sorted in ascending order * @param target an integer * @return an integer */ public int closestNumber(int[] A, int target) { // Write your code here if(A == null || A.length == 0) return -1; int left = 0, right = A.length - 1, mid; while(left < right){ mid = left + (right - left) / 2; if(A[mid] < target){ left = mid + 1; } else{ right = mid; } } // when left == right, this is the first position that target can be insert if(right > 0 && (A[right] - target) > (target - A[right - 1])) return right - 1; else return right; }} |
Closest Number in Sorted Array
标签:and mon text sel oat contain find [] out
原文地址:http://www.cnblogs.com/zhxshseu/p/e215a1d1097b67b1ac7d67e99929f426.html