[프로그래머스-JAVA] 해시

유진·2024년 7월 18일
0

코딩테스트

목록 보기
3/18

📝 프로그래머스 - JAVA

폰켓몬 (Level 1)

import java.util.Set;
import java.util.HashSet;

class Solution {
    public int solution(int[] nums) {
        Set<Integer> uniqueNums = new HashSet<Integer>();
        for (int num : nums) {
            uniqueNums.add(num);
        }
        
        int maxUniqueCount = uniqueNums.size();
        int halfLength = nums.length / 2;
      
        int answer = Math.min(maxUniqueCount, halfLength);
        
        return answer;
    }
}

완주하지 못한 선수 (Level 1)

import java.util.HashMap;

class Solution {
    public String solution(String[] participant, String[] completion) {
        String answer = "";
        HashMap<String, Integer> hm = new HashMap<>();
        for (String player : participant) hm.put(player, hm.getOrDefault(player, 0) + 1);
        for (String player : completion) hm.put(player, hm.get(player) - 1);

        for (String key : hm.keySet()) {
            if (hm.get(key) != 0){
                answer = key;
                break;
            }
        }
        return answer;
    }
}

전화번호 목록 (Level 2)

import java.util.HashMap;

class Solution {
    public boolean solution(String[] phone_book) {
        HashMap<String, Integer> hm = new HashMap<>();
        
        // 1. Add all phone numbers to the hash map
        for (String nums : phone_book) {
            hm.put(nums, 1);
        }
        
        // 2. Check for prefixes
        for (String nums : phone_book) {
            StringBuilder prefix = new StringBuilder();
            for (int i = 0; i < nums.length() - 1; i++) { // -1 to exclude the number itself
                prefix.append(nums.charAt(i));
                if (hm.containsKey(prefix.toString())) {
                    return false; // If any prefix exists in the map, return false
                }
            }
        }
        
        return true; // If no prefix is found, return true
    }
}

의상 (Level 2)

import java.util.HashMap;

class Solution {
    public int solution(String[][] clothes) {
        HashMap<String, Integer> hm = new HashMap<>();
        
        // 1. Add all clothes to the hash map
        for (String[] item : clothes) {
            String type = item[1];
            hm.put(type, hm.getOrDefault(type, 0) + 1);
        }
        
        int answer = 1;
        // 2. Calculate the number of combinations
        for (int count : hm.values()) {
            System.out.println(hm.values());
            answer *= (count + 1); // (count + 1) because we can choose to not wear any of this type
        }
        
        return answer - 1; // subtract 1 to exclude the case where no clothes are worn
    }
}
profile
유진진입니덩

0개의 댓글