zoukankan      html  css  js  c++  java
  • 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.

    分析

    使用binary Search 找到可以插入 target 的 position, 例如是 i, 那么,从i(包括i)到后面,都是大于等于target的数字
    1 如果 i == 0, return i,因为A[i]一定是最接近 target的数字,后面的数字都大于A[i]
    2 如果 i > =,那么需要考虑A[i] 和 A[i - 1] 哪个更接近 target,就返回哪一个
    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;
        }
    }




  • 相关阅读:
    转高少公众号【影响个人超速成长的三个因素】
    并发-ThreadLocal源码分析
    并发-CountDownLatch、CyclicBarrier和Semaphore
    并发-阻塞队列源码分析
    并发-线程池源码分析
    并发-ConcurrentHashMap源码分析
    并发-HashMap和HashTable源码分析
    《java并发编程实战》读书笔记
    《大型网站系统与JAVA中间件实践》读书笔记-数据访问层
    tomcat常用配置详解和优化方法
  • 原文地址:https://www.cnblogs.com/zhxshseu/p/e215a1d1097b67b1ac7d67e99929f426.html
Copyright © 2011-2022 走看看