Software Engineering/Algorithm

[LeetCode] #2248 Intersection of Multiple Arrays

devhrkim 2024. 6. 23. 12:56

풀이

class Solution {
    public List<Integer> intersection(int[][] nums) {
        HashMap<Integer, Integer> hashMap = new HashMap<>();
        ArrayList<Integer> answer = new ArrayList<>();
        int k = nums.length;
        for(int i=0;i<nums.length;i++) {
            for(int j=0;j<nums[i].length;j++)
                hashMap.put(nums[i][j], hashMap.getOrDefault(nums[i][j], 0)+1);
        }
        for(Integer key: hashMap.keySet()) {
            if(k == hashMap.get(key))
                answer.add(key);
        }
        Collections.sort(answer);
        return answer;
    }
}

 

다른 사람 풀이 for문

for (int[] arr: nums) {
    for (int x: arr) {
        counts.put(x, counts.getOrDefault(x, 0) + 1);
    }
}