Linear search in Java Count elements of an array in another one

Implement a method to search the count of occurrence values from the first array in the second one. The method must return an array of counts with the same size as the first array.

Both arrays are not empty; values may repeat in arrays.

Sample Input 1:

15 10 18 17 15
10 10 15 10 17 17
Sample Output 1:

1 3 0 2 1

import java.util.Arrays;
import java.util.Scanner;

public class Main {

    public static int[] countOccurrences(int[] first, int[] second) {
        int[] counts = new int[first.length];
        Arrays.fill(counts, 0);

        for (int i = 0; i < first.length; ++i) {
            for (int j = 0; j < second.length; ++j) {
                if (first[i] == second[j]) {
                    ++counts[i];
                }
            }
        }

        return counts;
    }

    public static void main(String[] args) {
        final Scanner scanner = new Scanner(System.in);

        final int[] first = Arrays.stream(scanner.nextLine().split("\\s+"))
                .mapToInt(Integer::parseInt)
                .toArray();
        final int[] second = Arrays.stream(scanner.nextLine().split("\\s+"))
                .mapToInt(Integer::parseInt)
                .toArray();
        final String result = Arrays.toString(countOccurrences(first, second))
                .replace(", ", " ")
                .replace("[", "")
                .replace("]", "");

        System.out.println(result);
    }
}
posted @ 2020-08-14 07:44  longlong6296  阅读(96)  评论(0)    收藏  举报