Number of occurrences in the sorted array-Sword point offer

Source: Internet
Author: User

Number of occurrences of numbers in a sorted array title description

Counts the number of occurrences of a number in a sorted array.

Ideas
    1. To handle an array that has been ordered, consider the idea of binary search
    2. Find the first position of this number with a binary search, and then find the last position that appears, you can get this number several times, so the time complexity is O (LOGN)
    3. Note that the number does not appear in the array
Code
PublicClass Solution {PublicIntGetnumberofk(int []Array,int k) {int num =0;if (Array = = NULL | |Array.Length = =0) {return num; }int FIRSTK = GETFIRSTK (Array, K,0,Array.Length-1);int LASTK = GETLASTK (Array, K,0,Array.Length-1); System.out.println ("First:" + FIRSTK +"LASTK:" + LASTK);if (Firstk >-1 && lastk >-1) {return LASTK-FIRSTK +1; }return num; }PublicIntGetfirstk(int[] Data,int k,int start,int end) {if (Start > End) {Return-1; }int Midindex = (start + end)/2;int middata = Data[midindex];if (Middata = = k) {if (Midindex >0 && Data[midindex-1]! = k) | | Midindex = =0) {return midindex; }else {end = Midindex-1; } }Elseif (Middata > k) {end = Midindex-1; }else {start = Midindex +1; }return Getfirstk (data, K, start, end); }PublicIntGetlastk(int[] Data,int k,int start,int end) {if (Start > End) {Return-1;} int Midindex = (start + end)/2; int middata = Data[midindex]; if (Middata = k) {if (Midindex < data.length-1 && data[midindex + 1]! = k) | | Midindex = = data.length-1) {return Midindex;} else {start = Midindex + 1;}} else if (Middata > k) {end = Midindex-1; } else {start = Midindex + 1;} return getlastk (data, K, start, end);}}        

Number of occurrences of a number in a sorted array-Sword point offer

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.