# Number of occurrences of the number in the sorted array

Source: Internet
Author: User

Topic

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

Solving

Method One: Violence
Linear traversal
Method 2:2 Division Method
To find out the left and right boundary respectively

`` Public classSolution { Public intGETNUMBEROFK (int[]Array,intK) {if(Array= = Null| |Array. length==0)return 0;intLow =0;intHigh =Array. Length-1;intL = Left (Array, low,high,k);if(L ==-1)return 0;intR = Right (Array, l,high,k);returnR-l +1; }//Seek left Border     Public intLeftint[]Array,intLow,intHighintK) {if(Array[Low] = = k)returnLow while(Low <= High) {intMID = low + (high-low)/2;if(Mid >=1&&Array[mid-1]!=k &&Array[Mid] ==k)//mid-1 cross-border to judge                returnMidif(Array[mid] >=k) {//Consider equalsHigh = mid-1; }Else{Low = mid +1; }        }return-1; }//Seek right border     Public intRightint[]Array,intLow,intHighintK) {if(Array[high] = = k)returnHigh while(Low <= High) {intMID = low + (high-low)/2;if(Mid +1<Array. length &&Array[Mid]==k &&Array[mid+1]!=k)//Mid + 1 out of bounds to judge                returnMidif(Array[mid] >k) {high = mid-1; }Else{//equals to be considered hereLow = mid +1; }        }return-1; }}``

Of course, you can also find a boundary and then line it up.

Number of occurrences of the number in the sorted array

Related Keywords:

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.