-
section3.2알고리즘 2025. 8. 9. 19:59
A, B 두 개의 집합이 주어지면 두 집합의 공통 원소를 추출하여 오름차순으로 출력하는 프로그램을 작성하세요. 입력 첫 번째 줄에 집합 A의 크기 N(1<=N<=30,000)이 주어집니다. 두 번째 줄에 N개의 원소가 주어집니다. 원소가 중복되어 주어지지 않습니다. 세 번째 줄에 집합 B의 크기 M(1<=M<=30,000)이 주어집니다. 네 번째 줄에 M개의 원소가 주어집니다. 원소가 중복되어 주어지지 않습니다. 각 집합의 원소는 1,000,000,000이하의 자연수입니다. 출력 두 집합의 공통원소를 오름차순 정렬하여 출력합니다. 예시 입력 1 5 1 3 9 5 2 5 3 2 5 7 8 예시 출력 1 2 3 5ANSWER
public class QuestionV2 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] nArr = new int[n]; for (int i=0; i<n; i++) { nArr[i] = sc.nextInt(); } int m = sc.nextInt(); int[] mArr = new int[m]; for (int i=0; i<m; i++) { mArr[i] = sc.nextInt(); } for (int a : solution(n, nArr, m, mArr)) { System.out.print(a + " "); } } public static ArrayList<Integer> solution (int n, int[] nArr, int m, int[] mArr) { ArrayList<Integer> answer = new ArrayList<>(); // 오름차순 정렬 Arrays.sort(nArr); Arrays.sort(mArr); int p1 = 0; int p2 = 0; while (p1<n && p2<m ) { if (nArr[p1] == mArr[p2]) { answer.add(nArr[p1++]); p2++; } else if (nArr[p1] < mArr[p2]) { p1++; } else { p2++; } } return answer; } }- 로직은 정말 쉽게 짰는데,, 마지막 if 문에서 nArr 과 mArr 오타가 있었고 그거 발견하느라 시간이 너무 오래 걸렸다... 앞으로 변수 이름 제대로 구분할 수 있도록 이름 짓기
SOLUTION
public class Answer2 { public static void main(String[] args) { Answer2 T = new Answer2(); Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] a = new int[n]; for (int i=0; i<n; i++) { a[i] = sc.nextInt(); } int m = sc.nextInt(); int[] b = new int[m]; for (int i=0; i<m; i++) { b[i] = sc.nextInt(); } for (int x : T.Solution(n, m, a, b)) { System.out.println(x + " "); } } 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 { p2++; } } return answer; } }728x90'알고리즘' 카테고리의 다른 글
section3.4 (1) 2025.08.13 section3.3 (0) 2025.08.13 section3.1 (2) 2025.08.09 section4.3 (3) 2025.08.07 section4.2 (0) 2025.08.07