Returns the number of times a number appears in an ordered array using the binary method.

Source: Internet
Author: User

Returns the number of times a number appears in an ordered array using the binary method.
1. Problem Description

In a given sorted array, find the number of occurrences of the specified number. For example, in the array [1, 2, 3, 4, 4, 4, 4, 6, 8, 9], 4 appears four times.

2. ideas and methods

This problem can be improved on the basis of the binary method. Assume that array a is an incremental series and the number to be searched is num. You can find the starting position and last position of num in array a respectively, calculate the number of times the numeric num appears in array a by the difference between the two.
The c ++ code is as follows:

# Include
  
   
# Include
   
    
# Include
    
     
# Include
     
      
# Include
      
        # Include
       
         # Include
        Using namespace std; // queries the number of times a specified number appears in an ordered array. isLeft marks the leftmost and rightmost int FindCntofNum (int a [], int len, int num, bool isLeft) {int left = 0, right = len-1; int pos, mid; while (left <= right) // Binary Search {mid = (left + right)/2; if (a [mid] <num) {left = mid + 1;} else if (a [mid]> num) {right = mid-1 ;} else {pos = mid; if (isLeft) // find the leftmost value {right = mid-1;} else // find the rightmost value {left = mid + 1 ;}}} return pos; // return the final position} int main () {int a [10] = {1, 2, 4, 4, 4, 6, 8, 9}; int left, right, dst = 4; left = FindCntofNum (a, 10, 4, true); right = FindCntofNum (a, 10, 4, false); printf ("count of number % d: % d \ n ", dst, right-left + 1); return 0 ;}
       
      
     
    
   
  

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.