01-10 04:27
Recent Posts
Recent Comments
๊ด€๋ฆฌ ๋ฉ”๋‰ด

miinsun

[Algorithm]์•Œ๊ณ ๋ฆฌ์ฆ˜ ์ž๋ฐ”_25 ๊ณตํ†ต ์›์†Œ ๊ตฌํ•˜๊ธฐ ๋ณธ๋ฌธ

Algorithm/Java

[Algorithm]์•Œ๊ณ ๋ฆฌ์ฆ˜ ์ž๋ฐ”_25 ๊ณตํ†ต ์›์†Œ ๊ตฌํ•˜๊ธฐ

miinsun 2022. 1. 4. 12:42

 

๐Ÿ’ฌ ๋ฌธ์ œ ์„ค๋ช…

A, B ๋‘ ๊ฐœ์˜ ์ง‘ํ•ฉ์ด ์ฃผ์–ด์ง€๋ฉด ๋‘ ์ง‘ํ•ฉ์˜ ๊ณตํ†ต ์›์†Œ๋ฅผ ์ถ”์ถœํ•˜์—ฌ ์˜ค๋ฆ„์ฐจ์ˆœ์œผ๋กœ ์ถœ๋ ฅํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์„ธ์š”.

 

 

 

๐Ÿ”จ ์ž…์ถœ๋ ฅ ์˜ˆ

์ž…๋ ฅ - ์ฒซ ๋ฒˆ์งธ ์ค„์— ์ง‘ํ•ฉ A์˜ ํฌ๊ธฐ N(1<=N<=30,000)์ด ์ฃผ์–ด์ง‘๋‹ˆ๋‹ค.

๋‘ ๋ฒˆ์งธ ์ค„์— N๊ฐœ์˜ ์›์†Œ๊ฐ€ ์ฃผ์–ด์ง‘๋‹ˆ๋‹ค. ์›์†Œ๊ฐ€ ์ค‘๋ณต๋˜์–ด ์ฃผ์–ด์ง€์ง€ ์•Š์Šต๋‹ˆ๋‹ค.

์„ธ ๋ฒˆ์งธ ์ค„์— ์ง‘ํ•ฉ B์˜ ํฌ๊ธฐ M(1<=M<=30,000)์ด ์ฃผ์–ด์ง‘๋‹ˆ๋‹ค.

๋„ค ๋ฒˆ์งธ ์ค„์— M๊ฐœ์˜ ์›์†Œ๊ฐ€ ์ฃผ์–ด์ง‘๋‹ˆ๋‹ค. ์›์†Œ๊ฐ€ ์ค‘๋ณต๋˜์–ด ์ฃผ์–ด์ง€์ง€ ์•Š์Šต๋‹ˆ๋‹ค.

๊ฐ ์ง‘ํ•ฉ์˜ ์›์†Œ๋Š” 1,000,000,000์ดํ•˜์˜ ์ž์—ฐ์ˆ˜์ž…๋‹ˆ๋‹ค.

5
1 3 9 5 2
5
3 2 5 7 8

์ถœ๋ ฅ - ๋‘ ์ง‘ํ•ฉ์˜ ๊ณตํ†ต์›์†Œ๋ฅผ ์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌํ•˜์—ฌ ์ถœ๋ ฅํ•ฉ๋‹ˆ๋‹ค.

2 3 5

 

 

โ€‹

๐Ÿ’ป Solution.java

import java.util.*;

public class Main {
	public ArrayList<Integer> solution(int n, int m, int[] arr1, int[] arr2) {
		ArrayList<Integer> answer = new ArrayList<>();
		Arrays.sort(arr1);
		Arrays.sort(arr2);

		int p1 = 0, p2 = 0;	
		while(p1 < n && p2 < m) {
			if(arr1[p1] == arr2[p2]) {
				answer.add(arr1[p1++]);
				p2++;
			}
			else if(arr1[p1] < arr2[p2]) {
				p1++;
			}
			else
				p2++;
		}
		
        return answer;
	}
	
	public static void main(String[] args){
		Main main  = new Main();
		Scanner sc =new Scanner(System.in);
		
		int n = sc.nextInt();
		int[] arr1 = new int[n];

		for(int i = 0; i < n; i++) {
			arr1[i] = sc.nextInt();
		}
		
		int m = sc.nextInt();
		int[] arr2 = new int[m];
		for(int i = 0; i < m; i++) {
			arr2[i] = sc.nextInt();
		}

		for(int num : main.solution(n , m, arr1, arr2)) {
			System.out.print(num + " ");
		}
		
		System.out.println();
		
		sc.close();
		return ;
	}
}

 

 

 

Comments