leetcode 1207, Unique Number of Occurrences

NJW·2022년 11월 30일
0

코테

목록 보기
118/170

들어가는 말

배열 숫자의 갯수가 중복이 안 되면 true를, 중복이 되면 false를 반한하는 문제다. 특정한 알고리즘 없이 HashMap과 HashSet 자료구조를 이용해서 풀었다.

코드 설명

  1. 먼저 숫자가 얼마나 반복이 되는지르 알아야 한다. 이때는 HashMap을 이용한다.
        for(int i : arr){
            if(map.containsKey(i)){
                int tmp = map.get(i);
                map.put(i, tmp+1);
            }else{
                map.put(i, 1);
            }
        }
  1. 그리고 반복된 갯수가 중복이 되는지를 알아야 한다. 만일 반복이 된다면 false를 반환하고 아니라면 true를 반환한다. 이때는 HahsSet을 이용한다.
        for(int key : map.keySet()){
            if(hashset.add(map.get(key))){
                continue;
            }else{
                return false;
            }
        }

        return true;

전체 코드

class Solution {
    public boolean uniqueOccurrences(int[] arr) {
        Map<Integer, Integer> map = new HashMap<>();
        HashSet<Integer> hashset = new HashSet<>();

        for(int i : arr){
            if(map.containsKey(i)){
                int tmp = map.get(i);
                map.put(i, tmp+1);
            }else{
                map.put(i, 1);
            }
        }

        for(int key : map.keySet()){
            if(hashset.add(map.get(key))){
                continue;
            }else{
                return false;
            }
        }

        return true;

    }
}
profile
https://jiwonna52.tistory.com/

0개의 댓글