-
Title Description:
-
counts the number of occurrences of a number in a sorted array.
-
Input:
-
Each test case consists of two lines:
The first line has 1 integer n, which represents the size of the array. 1<=n <= 10^6.
The second line has n integers representing the array elements, each of which is int.
The third line has 1 integer m, which indicates that there is an M query next. 1<=m<=10^3.
The following are m lines, each with an integer k representing the number to query.
-
Output:
-
For each test case, there are M-line outputs, 1 integers per line, representing the number of occurrences of that number in the array.
-
Sample input:
-
81 2 3 3 3 3 4 513
-
-
Sample output:
-
-
4
-
-
-
-
-
Source:http://ac.jobdu.com/problem.php?pid=1349#include <iostream> #include <cstdio>using namespace Std;bool Flag1 = True;bool Flag2 = true;int searchfirst (int a[], int n, int value) {int left = 0, right = N-1;while (left <= right) {int mid = (left + right)/2;if (A[mid] < value) left = mid + 1;else if (A[mid] > value) right = Mid-1;e Lse{if (a[mid-1]! = value | | mid = = 0)//mid==0return mid;elseright = Mid-1;}} Flag1 = False;return 0;} int searchlast (int a[],int n, int value) {int left = 0, right = N-1;while (left <= right) {int mid = (left + right)/2;i F (A[mid] < value) left = mid + 1;else if (A[mid] > value) right = Mid-1;else{if (A[mid + 1]! = value | | mid = = n)// Mid==nreturn Mid;elseleft = mid + 1;}} Flag2 = False;return 0;} int main () {int n, m;//n is the size of the array, M is the number of queries int k;//the number to query while (scanf ("%d", &n)!=eof) {int *array = new Int[n+1];for (int i = 0 ; I < n; i++) {scanf ("%d", array+i);} scanf ("%d", &m), while (m--) {scanf ("%d", &k); int first =searchfirSt (array,n,k); int last = Searchlast (array,n,k), if (!flag1 &&!flag2) printf ("0\n"); elseprintf ("%d\n", last- First + 1);}} return 0;}
-
-
The sword points to the offer surface Question 38: Number of occurrences of numbers in sorted arrays