[LeetCode] Intersection of Multiple Arrays

아르당·2026년 8월 21일

LeetCode

목록 보기
479/561
post-thumbnail

문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음

Problem

2차원 정수 배열 nums가 주어지고, nums[i]는 비어있지 않은 배열의 서로 다른 양의 정수이고, 각 nums 배열에 공통으로 나타나는 정수들을 오름차순으로 정렬한 리스트를 반환해라.

Example

#1
Input: nums = [[3, 1, 2, 4, 5], [1, 2, 3, 4], [3, 4, 5, 6]]
Output: [3, 4]

#2
Input: nums = [[1, 2, 3], [4, 5, 6]]
Output: []

Constraints

  • 1 <= nums.length <= 1000
  • 1 <= sum(nums[i].length) <= 1000
  • 1 <= nums[i][j] <= 1000
  • nums[i]의 모든 값은 고유하다.

Solved

class Solution {
    public List<Integer> intersection(int[][] nums) {
        int[] counts = new int[1001];
        int n = nums.length;
        
        for(int[] num : nums){
            for(int i : num){
                counts[i]++;
            }
        }

        List<Integer> result = new ArrayList<>();

        for(int i = 0; i < 1001; i++){
            if(counts[i] == n){
                result.add(i);
            }
        }

        return result;
    }
}
profile
내 마음대로 코드 작성하는 세상

0개의 댓글