https://www.acmicpc.net/problem/1270

코드설명

해시맵(HashMap)을 활용합니다.

 

과반수(T/2)가 넘을경우 해당 HashMap의 Key를 출력합니다.

코드

package Main;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;
 
public class Main {
	private static int N, M, C, T;
    private static int answer = 0;
    private static StringBuilder sb = new StringBuilder();
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());
        
        N = Integer.parseInt(st.nextToken());
        
        for(int i=0;i<N; i++) {
        	st = new StringTokenizer(br.readLine());
        	T = Integer.parseInt(st.nextToken());
        	long[] arr = new long[T];
        	for(int j=0;j<T;j++) {
        		arr[j] = Long.parseLong(st.nextToken());
        	}
        	
        	func(arr, T);
        }
        System.out.println(sb.toString());
    }
    
    public static void func(long[] arr, int arrSize) {
    	HashMap<Long, Integer> hashmap = new HashMap<>();
    	
    	for(int i=0;i<arr.length;i++) {
    		hashmap.put(arr[i], hashmap.getOrDefault(arr[i], 0) + 1);
    	}
    	for(Map.Entry<Long, Integer> entrySet : hashmap.entrySet()) {
    		if(entrySet.getValue() > arrSize / 2) {
    			sb.append(entrySet.getKey()).append("\n");
    			return ;
    		}
    	}    
    	sb.append("SYJKGW").append("\n");
    }
     
    
}

+ Recent posts