<섹션3-Two pointers, Sliding window> 2. 공통원소 구하기

조이·2022년 1월 6일
0

자바 알고리즘

목록 보기
26/41
post-thumbnail

2. 공통원소 구하기

<설명>

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

<입력>

첫 번째 줄에 집합 A의 크기 N(1<=N<=30,000)이 주어집니다.
두 번째 줄에 N개의 원소가 주어집니다. 원소가 중복되어 주어지지 않습니다.
세 번째 줄에 집합 B의 크기 M(1<=M<=30,000)이 주어집니다.
네 번째 줄에 M개의 원소가 주어집니다. 원소가 중복되어 주어지지 않습니다.
각 집합의 원소는 1,000,000,000이하의 자연수입니다.

<출력>

두 집합의 공통원소를 오름차순 정렬하여 출력합니다.

===================================================

<코드>

배열의 순서가 오름차순이 아니므로 먼저 오름차순으로 다시 정렬해준다. 공통원소를 구하는 것이므로 두 배열중 하나가 끝이면 끝난다. 같은 원소가 있다면 arraylist에 추가한 후 두 배열의 위치를 가리키는 p1과 p2를 모두 증가시킨다. 아니라면 더 작은 값을 가진 배열의 위치값을 증가시킨다.

import java.util.*;

class Main {	
	public ArrayList<Integer> solution(int num,int num2,int[] array1,int[] array2){
		ArrayList<Integer> answer=new ArrayList<>();
		int p1=0,p2=0;
		Arrays.sort(array1);
		Arrays.sort(array2);
		
		while(p1<num&&p2<num2) {
			if(array1[p1]==array2[p2]) {answer.add(array1[p1++]); p2++;}
			else if(array1[p1]<array2[p2]) p1++;
			else p2++; }
		
		return answer;
		
	}
		
		
	public static void main(String[] args) {
		Main main = new Main();
		Scanner scan = new Scanner(System.in);
	   
		int num=scan.nextInt();
	    int[] array1=new int[num];
		for(int i=0;i<num;i++) {
			array1[i]=scan.nextInt();
			}
		
	    int num2=scan.nextInt();
		int[] array2=new int[num2];
		for(int i=0;i<num2;i++) {
			array2[i]=scan.nextInt();
			}
		
		for(int x: main.solution(num,num2,array1,array2)) {
		System.out.print(x+" ");}
		}
}

<중요>

1) Arrays.sort(배열이름)

  • 배열을 오름차순으로 정렬한다.
profile
joy_study

0개의 댓글