[코테 풀이] Find Missing and Repeated Values

시내·2024년 6월 29일

Q_2965) Find Missing and Repeated Values

출처 : https://leetcode.com/problems/find-missing-and-repeated-values/

You are given a 0-indexed 2D integer matrix grid of size n * n with values in the range [1, n2]. Each integer appears exactly once except a which appears twice and b which is missing. The task is to find the repeating and missing numbers a and b.

Return a 0-indexed integer array ans of size 2 where ans[0] equals to a and ans[1] equals to b.

class Solution {
    public int[] findMissingAndRepeatedValues(int[][] grid) {
        int[] answer = new int[2];
        boolean[] visited = new boolean[grid.length * grid.length + 1];
        for (int v = 0; v < grid.length * grid.length + 1; v++) {
            visited[v] = false;
        }
        System.out.println(Arrays.toString(visited));
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[i].length; j++) {
                if (!map.containsKey(grid[i][j])) {
                    map.put(grid[i][j], 1);
                    visited[grid[i][j]] = true;
                } else map.put(grid[i][j], map.get(grid[i][j]) + 1);
            }
        }
        Iterator<Integer> it = map.keySet().iterator();
        while (it.hasNext()) {
            int next = it.next();
            if (map.get(next) == 2) {
                answer[0] = next;
                break;
            }
        }
        for (int j = 1; j < visited.length; j++) {
            if (!visited[j]) answer[1] = j;
        }
        return answer;
    }
}
profile
contact 📨 ksw08215@gmail.com

0개의 댓글