🌞Algorithm/🔥Baekjoon

[Baekjoon] 12596_Odd Man Out (Large)

뿌야._. 2025. 3. 20. 21:54
문제(출처: https://www.acmicpc.net/problem/12596)

< Odd Man Out (Large) >

 

문제 풀이 

 

HashMap을 사용하여 하나만 나온 숫자를 찾는다.

 

만약 입력이 

1 3 3이라면 1을 출력한다.

 

my solution (Java)

 import java.io.BufferedReader;
 import java.io.BufferedWriter;
 import java.io.IOException;
 import java.io.InputStreamReader;
 import java.io.OutputStreamWriter;
 import java.util.ArrayList;
 import java.util.Collections;
 import java.util.Comparator;
 import java.util.HashMap;
 import java.util.StringTokenizer;
 
 public class _12596_ { // Odd Man Out (Large)
 
 	public static void main(String[] args) throws IOException {
 		BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
 		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
 		StringTokenizer st;
 
 		int N = Integer.parseInt(bf.readLine());
 
 		for (int i = 0; i < N; i++) {
 			int G = Integer.parseInt(bf.readLine());
 
 			HashMap<Integer, Integer> map = new HashMap<>();
 			st = new StringTokenizer(bf.readLine());
 			for (int j = 0; j < G; j++) {
 				int C = Integer.parseInt(st.nextToken());
 
 				if (map.containsKey(C)) {
 					map.replace(C, map.get(C) + 1);
 				} else {
 					map.put(C, 1);
 				}
 			}
 
 			ArrayList<Integer> list = new ArrayList<>(map.keySet());
 			Collections.sort(list, new Comparator<Integer>() {
 				@Override
 				public int compare(Integer o1, Integer o2) {
 					return map.get(o1) - map.get(o2);
 				}
 			});
 			bw.write("Case #" + (i + 1) + ": " + list.get(0) + "\n");
 		}
 		bw.flush();
 	}
 }
변수)
N : 테스트 케이스 수
G : 게스트 수
map : HashMap <Integer, Integer>
C : 초대 코드
list : HashMap key값 -> ArrayList

 

테스트 케이스 수 N을 입력받아 N만큼 다음 과정을 반복한다.

 

1) 게스트 수 G를 입력받는다.

2) G만큼 초대 코드를 입력받아 초대 코드가 HashMap에 key 값으로 존재한다면 value를 1 증가시키고, key 값으로 없다면 추가한다.

3) HashMap의 key값들을 ArrayList로 변환한다.

4) ArrayList를 HashMap의 value 기준 오름차순으로 정렬한다.

5) 최종 ArrayList의 0번째 값을 출력한다.



 

'🌞Algorithm > 🔥Baekjoon' 카테고리의 다른 글

[Baekjoon] 11597_Excellence  (0) 2025.03.24
[Baekjoon] 6123_O Those Fads  (0) 2025.03.21
[Baekjoon] 26975_Cow College  (0) 2025.03.18
[Baekjoon] 19709_LunchBox  (0) 2025.03.14
[Baekjoon] 12724_Minimum Scalar Product (Large)  (0) 2025.03.13