미소를뿌리는감자의 코딩

[프로그래머스 2025/01/16] 완주하지 못한 선수 본문

코딩 테스트/프로그래머스

[프로그래머스 2025/01/16] 완주하지 못한 선수

미뿌감 2025. 1. 16. 17:59
728x90

1. 문제

https://school.programmers.co.kr/learn/courses/30/lessons/42576

 

프로그래머스

SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr

 

2. 접근 방법

처음에는 .remove를 바탕으로 문제를 해결해 보고자 하였다.

 

 

import java.util.*;
import java.util.Map.Entry;
import java.util.stream.Collectors;

class Solution {
    public static String solution(String[] participant, String[] completion) {
    	
        Map<String, Long> participantCount = Arrays.stream(participant)
        		.collect(Collectors.groupingBy(name -> name, Collectors.counting()));
        Map<String, Long> completionCount = Arrays.stream(completion)
        		.collect(Collectors.groupingBy(name -> name, Collectors.counting()));
        
        for (Entry<String, Long> entry : participantCount.entrySet()) {
        	Long completionValue = completionCount.getOrDefault(entry.getKey(), 0L);
        	if (!completionValue.equals(entry.getValue())) {
        		return entry.getKey();
        	}
        }
        return "";
    }
    
    public static String solution2(String[] participant, String[] completion) {
    	Map<String, Long> participants = new HashMap<>();
    	Map<String, Long> completions = new HashMap<>();
    	
    	for(String p : participant) {
    		participants.put(p, participants.getOrDefault(p, 0L)+1);
    	}
    	
    	for (String c : completion) {
    		completions.put(c, completions.getOrDefault(c, 0L)+1);
    	}
    	
    	for (Entry<String, Long> p : participants.entrySet()) {
    		Long completionCnt = completions.getOrDefault(p.getKey(), 0L);
    		if (!p.getValue().equals(completionCnt)) {
    			return p.getKey();
    		}
    	}
    	return "";
    	
    }
    
    /*
     * main 메서드: static으로 정의되어 있으며, 프로그램의 시발점.
     * main 메서드가 실행될 때, 객체 인스턴스를 생성하지 않고 실행되므로, main메서드가 호출하려는 메서드도 객체 없이
     * 호출할 수 있도록 static 이어야 한다.
     * 
     * {"leo", "leo", "leo", "kitty"}
     * {"leo":3, "kitty" :1}
     * {"leo":2, kitty":1
     * 
     */
    public static void main(String[] args) {
    	String[] participant = {"leo", "kiki", "eden"};
    	String[] completion = {"eden", "kiki"};
    	System.out.println(Solution.solution(participant, completion));
    }
}

/*
 * groupingBy 그룹화 하는 작업을 수행
 */
728x90