[Java] two pointers 알고리즘 2

urzi·2022년 3월 25일
0

PS

목록 보기
6/36

문제

A, B 두 개의 집합이 주어지면 두 집합의 공통 원소를 추출하여 오름차순으로 출력하는 프로그램을 작성하세요.

풀이

일단 두 배열 모두 오름차순으로 정렬되어 있어야 한다.
이후에 둘 중에 하나라도 포인터가 배열 끝에 도달할 때 까지 while문을 돌려준다.
그 다음엔 두 값이 같을 때에만 answer 배열에 넣어준다.
그 다음은 두 배열의 값중 작은 배열의 포인터만 증가시켜준다. 오름차순이 되어있기 때문이다.

코드

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

class Main {

    public 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 if ((a[p1] > b[p2])){
                p2++;
            }
        }

        return answer;
    }

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

        int n = scanner.nextInt();
        int[] a = new int[n];
        for (int i = 0; i < n; i++) {
            a[i] = scanner.nextInt();
        }

        int m = scanner.nextInt();
        int[] b = new int[m];
        for (int i = 0; i < m; i++) {
            b[i] = scanner.nextInt();
        }

        for (int x : solution.solution(n, m, a, b)) {
            System.out.print(x + " ");
        }
    }
}


profile
Back-end Developer

1개의 댓글

comment-user-thumbnail
2022년 3월 28일

사랑해요♡

답글 달기