๊ด€๋ฆฌ ๋ฉ”๋‰ด

โœ๐Ÿป๊ธฐ๋กํ•˜๋Š” ๋ธ”๋กœ๊ทธ

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค - ํ•ด์‹œ] Lv2.์œ„์žฅ ๋ณธ๋ฌธ

์•Œ๊ณ ๋ฆฌ์ฆ˜

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค - ํ•ด์‹œ] Lv2.์œ„์žฅ

์ฉ์‹œํ‚ด 2022. 7. 26. 22:26
728x90

์ข…๋ฅ˜๋ณ„ ๊ฐ€์ง“์ˆ˜๋ฅผ ์ฒดํฌํ•˜๊ธฐ ์œ„ํ•ด Map์„ ์‚ฌ์šฉํ•œ๋‹ค. 

Map์˜ ํ‚ค๊ฐ€ ๊ณตํ†ต์œผ๋กœ ๋ฌถ์„์ˆ˜ ์žˆ๋Š” ์ข…๋ฅ˜๊ฐ€ ๋œ๋‹ค.

import java.util.*;
class Solution {
    public int solution(String[][] clothes) {
        Map<String, Integer> counts = new HashMap<String, Integer>();
        
        for(String[] s : clothes) {
            String type = s[1];
            counts.put(type, counts.getOrDefault(type, 0) + 1);
        }
        
        int answer = 1;
        for(Integer num : counts.values()) {
            answer *= num + 1;//์‚ฌ์šฉํ•˜์ง€ ์•Š๋Š” ๊ฒฝ์šฐ ์ถ”๊ฐ€ํ•˜์—ฌ ๊ณฑํ•œ๋‹ค.
        }
        return answer-1 ;//๋ชจ๋‘๋‹ค ์‚ฌ์šฉํ•˜์ง€ ์•Š๋Š” ๊ฒฝ์šฐ๋ฅผ ๋บ€๋‹ค.
    }
}

์ƒˆ๋กญ๊ฒŒ ์•Œ๊ฒŒ๋œ๊ฒƒ

Map.getOrDefault(key๊ฐ’, default value)

map์˜ ๊ฐ’์„ ๊บผ๋ƒˆ์„ ๋•Œ null์ธ ๊ฒฝ์šฐ ์‚ผํ•ญ ์—ฐ์‚ฐ์ž๋ฅผ ํ†ตํ•ด ๊ธธ์–ด์กŒ์ง€๋งŒ getOrDefault๋ฉ”์„œ๋“œ๋ฅผ ํ†ตํ•ด ์ฝ”๋“œ๋ฅผ ์ค„์ผ ์ˆ˜ ์žˆ๋‹ค.

 

stream์„ ์‚ฌ์šฉํ•œ ๋ฆฌํŒฉํ„ฐ๋ง

import java.util.*;
class Solution {
    public int solution(String[][] clothes) {
       int answer = Arrays.stream(clothes)
           .map(c ->c[1])
           .distinct()
           .map(type -> (int) Arrays.stream(clothes).filter(c -> c[1].equals(type)).count())
           .map(c -> c +1)
           .reduce(1,(c,n) -> c * n);
           return answer -1;
    }
}

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค java ์ปค๋ฎค๋‹ˆ๋ง ๊ฐ•์˜๋ฅผ ๋“ฃ๊ณ  ์ •๋ฆฌํ•œ ๋‚ด์šฉ์ž…๋‹ˆ๋‹ค.

728x90
๋ฐ˜์‘ํ˜•