Closet number in sorted array

Source: Internet
Author: User

Closest number in Sorted Array

Given a target number and an integer array a sorted in ascending order, find the index in i a such that a[i] is closes T to the given target.

Return-1 If there is no element in the array.

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 .

Note

There can duplicate elements in the array, and we can return any of the indices with same value.

 1 classSolution {2  Public: 3     /** 4 * @param A integer array sorted in ascending order 5 * @param target an integer 6 * @return A Integer 7*/ 8     intClosestnumber (vector<int>& A,inttarget) { 9         if(a.size () = =0) {Ten             return-1; One         } A          -         intb =0, E = A.size ()-1; -          while(b +1<e) { the             intMid = B + (e-b)/2; -             if(A[mid] = =target) { -                 returnmid; -}Else if(A[mid] <target) { +b =mid; -}Else { +E =mid; A             } at         } -         if(ABS (A[b]-target) < ABS (A[e]-target)) { -             returnb; -}Else { -             returne; -         } in     } -};

Closet number in sorted array

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.