개발놀이터

3-2. 공통 원소 구하기 본문

기타/코딩테스트

3-2. 공통 원소 구하기

마늘냄새폴폴 2023. 2. 18. 09:38

package 배열응용3장.공통원소구하기3다시2.my;

import java.util.ArrayList;
import java.util.Scanner;

public class Main {

    /**
     * -내 풀이-
     * 도저히 생각이 나지 않아서 포기했다.
     *
     * -선생님 풀이-
     * 이번에도 two pointers algorithm 을 사용한 문제였다.
     * 이번에 눈여겨 볼 점은 어떤 배열을 오름차순으로 정렬하기 위해서는 Arrays 클래스의 sort 메서드를 사용하면 된다는 것과
     * 교집합을 찾는 문제이기 때문에 p1 과 p2 가 같은 경우 p1, p2 둘을 동시에 증가시켜야 했다는 점이다.
     *
     * 그리고 p1 과 p2 중 작은 쪽을 하나 증가시켜야 한다는 점도 인상깊었다.
     *
     * int p1 = 0, p2 = 0;
     * while (p1 < n && p2 < m) {
     *     if (a[p1] == b[p2]) {
     *         answer.add(a[p1++]);
     *         p2++;
     *     }
     *     else if (a[p1] < b[p2]) {
     *         p1++;
     *     }
     *     else {
     *         p2++;
     *     }
     * }
     */

    public static void main(String[] args) {
        Scanner kb = new Scanner(System.in);
        int num1 = kb.nextInt();
        long[] arr1 = new long[num1];
        for (int i = 0; i < num1; i++) {
            arr1[i] = kb.nextInt();
        }
        int num2 = kb.nextInt();
        long[] arr2 = new long[num2];
        for (int i = 0; i < num2; i++) {
            arr2[i] = kb.nextInt();
        }

        for (int x : solution(num1, num2, arr1, arr2)) {
            System.out.print(x + " ");
        }
    }

    private static ArrayList<Integer> solution(int num1, int num2, long[] arr1, long[] arr2) {
        ArrayList<Integer> answer = new ArrayList<>();
        int pt1 = 0, pt2 = 0;

        while (true) {
            if (arr1[pt1] == arr2[pt2++]) {

            }
        }

    }
}

 

package 배열응용3장.공통원소구하기3다시2.teacher;

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

public class Main {

    public static void main(String[] args) {
        Scanner kb = new Scanner(System.in);
        int n = kb.nextInt();
        int[] a = new int[n];
        for (int i = 0; i < n; i++) {
            a[i] = kb.nextInt();
        }
        int m = kb.nextInt();
        int[] b = new int[m];
        for (int i = 0; i < m; i++) {
            b[i] = kb.nextInt();
        }
        for (int  x : solution(n, m, a, b)) System.out.print(x + " ");
    }

    private static ArrayList<Integer> solution(int n, int m, int[] a, int[] b) {
        ArrayList<Integer> answer = new ArrayList<>();
        Arrays.sort(a);
        Arrays.sort(b);
        int p1 = 0, p2 = 0;

        while (p1 < n && p2 < m) {
            if (a[p1] == b[p2]) {
                answer.add(a[p1++]);
                p2++;
            }
            else if (a[p1] < b[p2]) {
                p1++;
            }
            else {
                p2++;
            }
        }

        return answer;
    }
}

 

'기타 > 코딩테스트' 카테고리의 다른 글

3-4. 연속 부분수열  (0) 2023.02.18
3-3. 최대 매출  (2) 2023.02.18
3-1. 두 배열 합치기  (0) 2023.02.18
2장 배열 주요개념 및 복습 노트  (0) 2023.02.14
2-12. 멘토링  (0) 2023.02.14