CD

Time Limit: 1 Sec Memory Limit: 128 MB
Jack and Jill have decided to sell some of their Compact Discs, while they still have some value. They have decided to sell one of each of the CD titles that they both own. How many CDs can Jack and Jill sell?
Neither Jack nor Jill owns more than one copy of each CD.

传送门:SHUOJ1058

Input

The input consists of a sequence of test cases. The first line of each test case contains two non-negative integers N and M, each at most one million, specifying the number of CDs owned by Jack and by Jill, respectively. This line is followed by N lines listing the catalog numbers of the CDs owned by Jack in increasing order, and M more lines listing the catalog numbers of the CDs owned by Jill in increasing order. Each catalog number is a positive integer no greater than one billion. The input is terminated by a line containing two zeros. This last line is not a test case and should not be processed.

Output

For each test case, output a line containing one integer, the number of CDs that Jack and Jill both own.

Sample Input

1
2
3
4
5
6
7
8
3 3
1
2
3
1
2
4
0 0

Sample Output

1
2

题解

10^6数据肯定得用O(nlogn)的算法
二分和Set or Map都可以做
下面是两种不同的做法:

AC code:(不包含输入类)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import java.io.*;  
import java.util.*;
public class Main {
//map做,查询是logn的
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
while(sc.hasNext()){
int n=sc.nextInt();
int m=sc.nextInt();
if(n==0&&m==0) break;
HashMap<Integer,Integer>map=new HashMap<Integer,Integer>();
for(int i=0;i<n+m;i++){
int temp=sc.nextInt();
if(!map.containsKey(temp)) map.put(temp, 1);
else map.put(temp, map.get(temp)+1);
}
Set<Integer>set=map.keySet();
int count=0;
for(int i:set){
if(map.get(i)!=1)count++;
}
System.out.println(count);
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import java.io.*;  
import java.util.*;
public class Main {
//二分
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
while(sc.hasNext()){
int n=sc.nextInt();
int m=sc.nextInt();
if(n==0&&m==0) break;
int[] shu1=new int [n];
int[] shu2=new int [m];
for(int i=0;i<n;i++) shu1[i]=sc.nextInt();
for(int i=0;i<m;i++) shu2[i]=sc.nextInt();
int count=0;
for(int i=0;i<n;i++) count+=binarysearch(shu1[i],shu2);
System.out.println(count);
}

}
public static int binarysearch(int temp,int []shu2){
int start=0;
int end=shu2.length;
while(start<=end){
int mid=(start+end)/2;
if(shu2[mid]==temp)return 1;
if(shu2[mid]<temp) start=mid+1;
else end=mid-1;
}
return 0;
}
}