[프로그래머스] 위장

monshell·2021년 11월 1일
0

ALGORITHM

목록 보기
13/17

문제 링크

문제 요약

  • 옷의 카테고리 별 갯수를 구하여 전체 경우의 수를 구한다

풀이 흐름

  • 입력으로 들어온 카테고리가 이전에 있던 카테고리인지, 새 카테고리인지, 같은 카테고리에 옷이 몇종류가 있는지를 빠르게 알아야 하니까 카테고리를 키로 갖는 맵을 사용한다.
  • 나는 카테고리 string을 key로 갖고, 그 카테고리에 해당하는 옷들의 이름을 전부 담은 List< String >을 value로 갖게 풀었는데, 해설을 보니 value로 그냥 카운트만 세는 Integer를 사용했다. 하긴 중복된 이름이 들어오지 않는다고 했으니까! 그리고 map에 count를 추가하는 코드는 아래와 같이 사용했다.
    counts.put(type, colunts.get(type) == null ? 0 : counts.get(type) + 1);
    // key에 해당하는 value가 null이라면 default 값을 사용하라. 
    -> counts.put(type, colunts.getOrDefault(type, 0) + 1);

코드
풀이 언어 : JAVA

public int solution(String[][] clothes) {

        Map<Integer, List<String>> map = new HashMap<>();
        for(int i=0;i<clothes.length;++i) {
        	
        	List<String> clothes_list;
        	int hash = clothes[i][1].hashCode();
        	
        	if(map.containsKey(hash))
        		clothes_list = map.get(hash);
        	else
        		clothes_list = new ArrayList<>();
        	
        	clothes_list.add(clothes[i][0]);
        	map.put(hash, clothes_list);
        }
        
        int answer = 1;
        Set<Integer> keySet  = map.keySet();
        for(int key : keySet ) {
        	answer *= map.get(key).size() + 1;
        }
        answer-=1;
        
        return answer;
    }

해설 풀이

public int solution(String[][] clothes) {

        Map<String, Integer> counts = new HashMap<>();
        
        for(String[] c : clothes) {
        	String type = c[1];
            counts.put(type, colunts.getOrDefault(type, 0) + 1);
        }
        
        int answer = 1;
        for(Integer c : counts.values()) {
        	answer *= c + 1;
        }
        answer -= 1;
    }

그리고 이걸 더 간결하게 줄이면 아래 코드

public int solution(String[][] clothes) {

        Map<String, Integer> counts = new HashMap<>();
        
        // 각 type은 여러개가 나올 수 있으니 중복을 제거(distinct) 하여 type값을 얻을 수 있다.
        // 특정 타입의 옷만 보겠다고 한다면
        // 전체 옷을 stream을 사용해서 filter로 첫번째 요소가 type과 같은지 보고
        // 그 count를 구하여 type에 대한 갯수를 구할 수 있다.
        // count()는 long으로 리턴되니까 int로 형변환 필요
        // 그리고 count 값에 1을 더해서 사용
        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;
    }

0개의 댓글

관련 채용 정보