Find out how many times a number appears in a sorted array

Source: Internet
Author: User

One, the problem description

Suppose that given an ordered array of integers arr, and an integer k, Q K appears in the array several times?

Second, solve the idea

The ① array is ordered, so you can consider using two points to find

② If you can find the index position of the first occurrence of K in the array first_index and the last occurrence of the index position Last_index

We can know the number of K occurrences: (last_index-first_index) + 1

In the case of ordered arrays, a binary lookup can be used to find the first occurrence of a number of index positions and the last occurrence of the index position. So the total time complexity is O (LOGN)

③ Special Case Considerations

What if K is not in the array? Array arr is null or array arr.length = = 0

Core idea: Solving the index position when K first appears

First find Arr[middle], if K is larger than the middle element, then on the right to find the first occurrence of K index position (recursion), if K is smaller than the middle element, then on the left to find ... (recursive).

if k = = Arr[middle], you need to determine whether arr[middle-1] is equal to K, if not equal to K, then middle is the first time K is the index, if equal to K, then continue to recursion on the left to find, but at this point to note that the left index is not To cross the border (middle = = Low, you can not go to the left to find).

The same can be solved, the index position of the last occurrence of K.

Three, complete code implementation

 Public classOccfreq {/*** Solve the index position of the first occurrence of K in arr *@paramArr ordered array *@paramK *@returnk The first occurrence of the index position, if K does not return in ARR-1*/     Public Static intGetFirst (int[] arr,intk) {        if(arr = =NULL|| Arr.length = = 0)            Throw NewIllegalArgumentException ("arr = = NULL or Arr.lenght = = 0"); returnGetFirst (arr, 0, Arr.length-1, K); }        Private Static intGetFirst (int[] arr,intLowintHighintk) {        intMiddle = (low + high)/2; if(middle = = Low | | middle = =High ) {            if(Arr[middle] = =k)returnMiddle; Else//throw new IllegalArgumentException (k + "not in arr");                return-1; }                if(Arr[middle] >k)returnGetFirst (arr, Low, middle-1, K); Else if(Arr[middle] <k)returnGetFirst (arr, middle + 1, high, k); Else        {            if(Arr[middle-1] = =k)returnGetFirst (arr, Low, middle-1, K); Else                returnMiddle; }    }        /*** Solve K index last occurrence in arr *@paramarr *@paramK *@returnk The last occurrence of the index in Arr, if K is not returned in Arr-1*/     Public Static intGetLast (int[] arr,intk) {        if(arr = =NULL|| Arr.length = = 0)            Throw NewIllegalArgumentException ("arr = = NULL"); returnGetLast (arr, 0, Arr.length-1, K); }    Private Static intGetLast (int[] arr,intLowintHighintk) {        intMiddle = (low + high)/2; //has been found to the far left or the far right.        if(middle = = Low | | middle = =High ) {            if(Arr[middle] = =k)returnMiddle; Else//throw new IllegalArgumentException (k + "not in arr");                return-1;//k not in Arr        }        if(Arr[middle] > K) {//keep looking on the left            returnGetLast (arr, Low, middle-1, K); }        Else if(Arr[middle] < K) {//keep looking on the right .            returnGetLast (arr, middle + 1, high, k); }        Else//k== Arr[middle]        {            if(Arr[middle + 1] = =k)returnGetLast (arr, middle + 1, high, k);//keep looking on the right .            Else                returnMiddle; }    }        /*** Solve K occurrences in arr array *@paramArr ordered array *@paramK *@returnnumber of occurrences of K in arr array*/     Public Static intFreqint[] arr,intk) {        intFirst_index =GetFirst (arr, k); intLast_index =GetLast (arr, k); if(First_index < 0 && Last_index < 0)            return0; returnLast_index-first_index + 1; }         Public Static voidMain (string[] args) {int[] arr = {2,4,5,6,8,8,8,9}; intFreqs = Freq (arr, 1);    System.out.println (FREQS); }}

Find out how many times a number appears in a 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.