二分搜索
Binary Search
You are given a sequence of n integers S and a sequence of different q integers T. Write a program which outputs C, the number of integers in T which are also in the set S.
Input
In the first line n is given. In the second line, n integers are given. In the third line q is given. Then, in the fourth line, q integers are given.
Output
Print C in a line.
Constraints
- Elements in S is sorted in ascending order
- n ≤ 100000
- q ≤ 50000
- 0 ≤ an element in S ≤ 109
- 0 ≤ an element in T ≤ 109
Sample Input 1
5 1 2 3 4 5 3 3 4 1
Sample Output 1
3
Sample Input 2
3 1 2 3 1 5
Sample Output 2
0
Notes
本题是一种更加快捷的查找方法,但要求查找序列一定要是有序的序列。这样才可以对半砍来分,从而达到logn的复杂度。
代码如下:
1 #include <iostream> 2 #include <cstdio> 3 #include <algorithm> 4 using namespace std; 5 6 const int maxn = 100000 + 5; 7 8 int n,sum = 0; 9 int a[maxn]; 10 11 bool find(int key){ 12 int l = 0,r = n; 13 while(l < r){ 14 int mid = (l+r)>>1; 15 if(a[mid] < key){ 16 l = mid+1; 17 } 18 else if(a[mid] > key){ 19 r = mid; 20 } 21 else{ 22 return true; 23 } 24 } 25 return false; 26 } 27 28 int main(){ 29 scanf("%d",&n); 30 for(int i = 0;i < n; i++){ 31 scanf("%d",&a[i]); 32 } 33 sort(a+1,a+n+1); 34 int q; 35 scanf("%d",&q); 36 for(int i = 0;i < q; i++){ 37 int key; 38 scanf("%d",&key); 39 if(find(key)){ 40 sum++; 41 } 42 } 43 printf("%d\n",sum); 44 }