신고 결과 받기 (자바)

김재현·2023년 12월 12일
0

알고리즘 풀이

목록 보기
49/89

문제

정답 코드

import java.util.*;
class Solution {
    public int[] solution(String[] id_list, String[] report, int k) {
        // 동일한 신고내역 제거
        String[] repo = Arrays.stream(report).distinct().toArray(String[]::new);

        // 맵에 신고자-신고내역 으로 저장
        Map<String, List<String>> repoMap = new HashMap<>();
            for (int j = 0; j < repo.length; j++) {
                String a = repo[j].split(" ")[0];
                String b = repo[j].split(" ")[1];

                // 비어있다면 put 아니면 더해줌
                repoMap.computeIfAbsent(a, value -> new ArrayList<>()).add(b);
            }

        // 신고내역 확인하며 카운트
        Map<String, Integer> countMap = new HashMap<>();
        for (Map.Entry<String, List<String>> entry : repoMap.entrySet()) {
            entry.getValue().stream().forEach(a -> {
                if (countMap.get(a) == null) {
                    countMap.put(a, 1);
                } else {
                    countMap.put(a, countMap.get(a) + 1);
                }
            });
        }

        // id_list의 이름으로 신고한 사람 중 카운트가 k이상인 것의 개수만큼 ++
        int[] result=new int[id_list.length];

        int i=0;
        for (String s : id_list) {
            List<String> stringList = repoMap.getOrDefault(s,null);

            if (stringList!=null) {
                int finalI = i;
                stringList.stream().forEach(a-> {
                    if (countMap.get(a)>=k) {
                        result[finalI]++;
                    }
                });
            }
            i++;
        }

        return result;
    }
}

이번 문제에서는 람다를 적극 활용했다.

  • stream.distinct() : 스트림에서 중복되는 요소들을 모두 제거해주고 새로운 스트림을 반환

  • computeIfAbsent:
    - 키가 존재 할 경우: 아무런 작업을 하지 않고 기존에 존재하는 Key의 Value를 리턴
    - 키가 존재하지 않을 경우: 람다식을 적용한 값을 해당 key에 저장한 후 newValue를 반환

  • 람다에는 변하지 않는 상수거나 그러한 값만 들어갈 수 있기 때문에 위와 같이 finalI를 따로 선언하여 대입했다.

다른 사람 풀이

class Solution {
    public int[] solution(String[] id_list, String[] report, int k) {
        List<String> list = Arrays.stream(report).distinct().collect(Collectors.toList());
        HashMap<String, Integer> count = new HashMap<>();
        for (String s : list) {
            String target = s.split(" ")[1];
            count.put(target, count.getOrDefault(target, 0) + 1);
        }

        return Arrays.stream(id_list).map(_user -> {
            final String user = _user;
            List<String> reportList = list.stream().filter(s -> s.startsWith(user + " ")).collect(Collectors.toList());
            return reportList.stream().filter(s -> count.getOrDefault(s.split(" ")[1], 0) >= k).count();
        }).mapToInt(Long::intValue).toArray();
    }
}

이렇게 getOrDefault를 사용해서 바로 카운트를 넣을 수 있구나!

stream의 filter도 사용 할 수 있겠구나!

profile
I live in Seoul, Korea, Handsome

0개의 댓글