본문 바로가기

Algorithms/11 Coding Interview (CS Dojo)

Common Elements in Two Sorted Arrays (Java)

Common Elements in Two Sorted Arrays (Java)

Write a function that returns the common elements (as an array) between two sorted arrays of integers (ascending order).

Example: The common elements between [1, 3, 4, 6, 7, 9] and [1, 2, 4, 5, 9, 10] are [1, 4, 9].


풀이

ascending order임으로 중복된 숫자는 안들어감

map 에 담아서 중복되는 게 있으면 list에 담아두고 이걸 나중에 array 변환 (list는 resizable하니까)


import java.util.ArrayList;

import java.util.HashMap;

import java.util.List;


public class CE {

    public static void main(String[] args) {

        // NOTE: The following input values are used for testing your solution.


        int[] array1A = {1, 3, 4, 6, 7, 9};

        int[] array2A = {1, 2, 4, 5, 9, 10};

        // commonElements(array1A, array2A) should return [1, 4, 9] (an array).


        int[] array1B = {1, 2, 9, 10, 11, 12};

        int[] array2B = {0, 1, 2, 3, 4, 5, 8, 9, 10, 12, 14, 15};

        // commonElements(array1B, array2B) should return [1, 2, 9, 10, 12] (an array).


        int[] array1C = {0, 1, 2, 3, 4, 5};

        int[] array2C = {6, 7, 8, 9, 10, 11};

        // common_elements(array1C, array2C) should return [] (an empty array).

    }


    // Implement your solution below.

    // NOTE: Remember to return an Integer array, not an int array.

    public static Integer[] commonElements(int[] array1, int[] array2) {

        Integer[] resultInArray = new Integer[0];

            List<Integer> tempList = new ArrayList<>();

        HashMap<Integer, Integer> map = new HashMap<>();

        for (int i : array1) {

            map.put(i, i);

        }

        for (int i : array2) {

            if (map.containsKey(i)) {

                tempList.add(i);

            }

        }

        resultInArray = new Integer[tempList.size()];

        for (int i = 0; i < tempList.size(); i++) {

            resultInArray[i] = tempList.get(i);

        }

        return resultInArray;

    }

}