티스토리 뷰

728x90

https://programmers.co.kr/learn/courses/30/lessons/42578

 

코딩테스트 연습 - 위장

 

programmers.co.kr


[ 나의 풀이 ]

공식을 찾아내는것이 포인트이다.

공식: (A+1)*(B+1) -1

import java.util.HashMap;
import java.util.Map;

class Solution {
    public int solution(String[][] clothes) {
        int answer = 1;
        
        Map<String, Integer> clothesMap = new HashMap<>();
        for(int i = 0; i < clothes.length; i++) {
            clothesMap.put(clothes[i][1], clothesMap.getOrDefault(clothes[i][1],0) + 1);
        }
        
        for(String cloth : clothesMap.keySet()) {
            answer *= (clothesMap.get(cloth) + 1);
        }
        return answer-1;
    }
}

[ Iterator 사용 풀이 ]

import java.util.HashMap;
import java.util.Map;
import java.util.Iterator;

class Solution {
    public int solution(String[][] clothes) {
        int answer = 1;
        
        Map<String, Integer> clothesMap = new HashMap<>();
        for(int i = 0; i < clothes.length; i++) {
            clothesMap.put(clothes[i][1], clothesMap.getOrDefault(clothes[i][1],0) + 1);
        }
        
        Iterator<Integer> it = clothesMap.values().iterator();
        while(it.hasNext()) {
            answer *= (it.next().intValue() + 1);
        }
        return answer-1;
    }
}

[ 람다 사용 풀이 ]

import java.util.Arrays;
import java.util.stream.Collectors;

class Solution {
    public int solution(String[][] clothes) {
        return Arrays.stream(clothes)
                .collect(Collectors.groupingBy(c -> c[1], Collectors.counting()))
                .values()
                .stream()
                .reduce(1L, (x, y) -> x * (y + 1)).intValue() -1;
    }
}
728x90

'코딩테스트' 카테고리의 다른 글

[프로그래머스] 기능개발  (0) 2022.04.19
[프로그래머스] 베스트앨범  (0) 2022.04.19
[LeetCode] Valid Palindrome  (0) 2022.03.31
[LeetCode] Group Anagrams  (0) 2022.03.31
[프로그래머스] 전화번호 목록  (0) 2022.03.31
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/10   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31