깊은바다거북
개발 공부 기록
깊은바다거북
전체 방문자
오늘
어제
  • 분류 전체보기 (219)
    • JAVA (9)
    • JavaScript (15)
    • 스파르타코딩클럽 (11)
      • [내일배움단] 웹개발 종합반 개발일지 (5)
      • [내일배움캠프] 프로젝트와 트러블 슈팅 (6)
    • SQL | NoSQL (4)
    • CS 등등 (0)
    • TIL | WIL (173)
    • 기타 에러 해결 (3)
    • 내 살 길 궁리 (4)

인기 글

최근 글

최근 댓글

태그

  • 혼자 공부하는 자바스크립트
  • Trie
  • Backtracking(백트래킹)
  • BFS(너비우선탐색)
  • DFS(깊이우선탐색)
  • BST(이진 탐색 트리)
  • TIT (Today I Troubleshot)
  • TypeScript
  • Binary Tree(이진 트리)
  • 자료 구조
  • 트러블 슈팅 Troubleshooting
  • 팀 프로젝트
  • POST / GET 요청
  • Leetcode
  • 최소 힙(Min Heap)
  • tree
  • 01. 미니 프로젝트
  • 재귀 함수
  • 최대 힙(Max Heap)
  • Til
  • leetcode-cli
  • 코딩테스트 연습문제
  • Inorder Traversal(중위 순회)
  • Linked List
  • 자잘한 에러 해결
  • 프로그래머스
  • Preorder Traversal(전위 순회)
  • 자바스크립트 기초 문법
  • 시간 복잡도
  • 점화식(Recurrence Relation)
hELLO · Designed By 정상우.
깊은바다거북

개발 공부 기록

[프로그래머스 Lv1] 신고 결과 받기
JAVA

[프로그래머스 Lv1] 신고 결과 받기

2022. 8. 27. 20:06

programmers Level 1


08.27.(토) 

무작정 작동하게끔만 풀어봤다. 

import java.util.HashSet;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.ArrayList;

class Solution {
    public int[] solution(String[] id_list, String[] report, int k) {

        // 0. report에서 중복 제거하기
        HashSet<String> report_unique = new HashSet<>(Arrays.asList(report));
        // System.out.println("중복을 제거한 report: " + report_unique);

        // 1. report에 등장한 아이디별로 신고당한 횟수 세기
        HashMap<String, Integer> reported_count = new HashMap<>(report.length);
        LinkedHashMap<String, ArrayList<String>> report_map = new LinkedHashMap<>(report.length);
        for (String pair : report_unique) {
            String reporter_id = pair.split(" ")[0];
            String reported_id = pair.split(" ")[1];
            // 1.1 신고자:[신고당한1, 신고당한2,...] 리스트 만들기
            if (report_map.containsKey(reporter_id)) {
                report_map.get(reporter_id).add(reported_id);
            } else {
                report_map.put(reporter_id, new ArrayList<String>(Arrays.asList(reported_id)));
            }

            // 1.2 신고당한 id별로 횟수 세기
            if (reported_count.containsKey(reported_id)) {
                reported_count.put(reported_id, reported_count.get(reported_id) + 1);
            } else {
                reported_count.put(reported_id, 1);
            }
        }

        // System.out.println("유저별 신고한 ID 리스트: " + report_map);
        // System.out.println("유저별 신고당한 횟수: " + reported_count);

        // 2.0 정지당한 자:
        ArrayList<String> banned = new ArrayList<>();
        for (String user : reported_count.keySet()) {
            if (reported_count.get(user) >= k) {
                banned.add(user);
            }
        }
        // System.out.println("정지당한 유저: " + banned);

        // 2. 신고한 자가 정지된 신고자를 몇이나 가지고 있는지 report_map에서 조사.
        int[] answer = new int[id_list.length];
        for (int i = 0; i < id_list.length; i++) {
            String user = id_list[i];
            if (!report_map.containsKey(user)) {
                answer[i] = 0;
            } else {
                ArrayList<String> intersection = new ArrayList<>(report_map.get(user));
                intersection.retainAll(banned); //신고자별 신고한 id ArryaList와 banned의 ArrayList의 교집합           
                answer[i] = intersection.size();
            }
        }
        return answer;
    }
}

 

새롭게 찾아 쓴(a.k.a. 구글링한) 코드:

  • 중복 제거할 때 HashSet에 배열 넣어 만들기.
  • HashMap 만들 때 길이를 인자로 넘겨줄 수 있다.
  • Map 계열의 메소드들:
    • 넣을 땐 put(키, 값)
    • 찾을 땐 get(키)
    • 키 전체를 루프 돌아야 할 땐 keySet()
    • 특정 키가 들었는지 검사할 땐 containsKey(키).
  • List 계열의 메소드들:
    • 넣을 땐 add(값)
    • 찾을 땐 get(인덱스)
    • 교집합만 남길 때 유용한 retainAll(리트스)
    • 길이 구할 땐 .length 아니고 .size()

 

아쉬운 점:

  • Arrays.asList()가 받는 인자와 리턴값이 정확히 어떻게 되는지, 그래서 HashSet과 ArrayList에는 어떻게 들어갈 수 있었는지 알아봐야겠다.
  • 기능별로 메소드를 따로 만들어볼 수도 있었을 것 같다. 

며칠 이론만 공부했더니, 지금은 코드를 자세히 다시 뜯어보기보다 문제를 더 풀어서 이미 알고 있는 것에 더 익숙해지고 싶다. 몇 주 뒤에는 위의 코드를 더 잘 고쳐볼 수 있지 않을까?

 


 

    'JAVA' 카테고리의 다른 글
    • 책 [Java의 정석 기초편] CH 6. 객체 지향 프로그래밍I
    • 배열 ↔ 리스트 형변환 모음
    • Class literal 이란 용어를 발굴하게 된 사정
    • 왜 Iterator가 clutter라는 걸까?
    깊은바다거북
    깊은바다거북

    티스토리툴바