1-3 交集

给定两个数组(数组中不包含相同元素),求两个数组的交集中元素的个数(即共同出现的数,如没有则输出为None) 如输入:
5
1 2 4 6 8
6
1 2 5 6 7 8
输出: 4

import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int m = scan.nextInt();
        //使用hash的思想,第一个数组中出现,标为1
        //check第二个数组的hash值是否为1 如果是则重复 用rcnt记录
        int[] hash = new int[100000];
        int temp = 0;
        for(int i = 0; i < m; i++) {
            temp = scan.nextInt();
            hash[temp] = 1;
        }

        int rcnt = 0;
        int n = scan.nextInt();
        for(int j = 0; j < n; j++) {
            temp = scan.nextInt();
            if(hash[temp] == 1) {
                rcnt++;
            }
        }
        if(rcnt > 0) {
            System.out.println(rcnt);
        }else {
            System.out.println("None");
        }

    }
}

猜你喜欢

转载自blog.csdn.net/qq_31474267/article/details/81032428
1-3