Number of times a number appears in the sorting Array

Source: Internet
Author: User

Count the number of times a number appears in the SORT array. Input: each test case contains two rows: the first row has an integer n, indicating the size of the array. 1 <= n <= 10 ^ 6. The second row has n integers, indicating the array elements. Each element is an int. The third row has an integer m, which indicates that there are m queries next. 1 <= m <= 10 ^ 3. There are m rows below, each row has an integer k, indicating the number of queries. Output: For each test case, the m-row output is available. Each row has an integer representing the number of times this number appears in the array. Sample input: 81 2 3 3 3 3 4 513 sample output: 4 idea: Use the bipartite method to locate a specific number, and then scan before and after to determine the number of numbers ~ ^_^ Code AC: [cpp] // use a 2-way method !! Pai_^ # include <stdio. h> # include <stdlib. h> int main () {long int n, I, cou, mid, low, high; int m, * num, k; while (scanf ("% ld ", & n )! = EOF) {num = (int *) malloc (sizeof (int) * n); for (I = 0; I <n; I ++) {scanf ("% d", & num [I]);} scanf ("% d", & m); while (m --) {scanf ("% d ", & k); low = 0; high = n-1; while (low <= high) {mid = (low + high)/2; if (k = num [mid]) {break;} else if (k> num [mid]) {low = mid + 1 ;} else {high = mid-1 ;}} cou = 0; I = mid; while (I <n) {if (num [I] = k) {cou ++; I ++;} else {break;} I = mid-1; while (I >= 0) {if (num [I] = k) {cou ++; I --;} else {break;} printf ("% d \ n", cou) ;}} 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.