코딩테스트 풀이/JAVA
[LeetCode/Easy] 2248. Intersection of Multiple Arrays
무지맘
2023. 4. 30. 18:15
1. Input
1) int[][] nums
2. Output
1) 모든 행에 나오는 정수를 담은 리스트를 반환
- 정렬은 오름차순으로 한다.
- 각 행에는 중복 요소가 없다.
3. Constraint
1) 1 <= nums.length <= 1000
2) 1 <= sum(nums[i].length) <= 1000
3) 1 <= nums[i][j] <= 1000
4. Example
Input: nums = [[3,1,2,4,5],[1,2,3,4],[3,4,5,6]] -> Output: [3,4]
Input: nums = [[1,2,3],[4,5,6]] -> Output: []
5. Code
1) 첫 코드(2023/04/30)
class Solution {
public List<Integer> intersection(int[][] nums) {
List<Integer> answer = new ArrayList<>();
HashMap<Integer,Integer> map = new HashMap<>();
for(int i=0 ; i<nums.length ; i++)
for(int j=0 ; j<nums[i].length ; j++)
map.put(nums[i][j], map.getOrDefault(nums[i][j],0)+1);
Iterator it = map.entrySet().iterator();
while(it.hasNext()){
Map.Entry e = (Map.Entry)it.next();
if((int)e.getValue()==nums.length)
answer.add((int)e.getKey());
}
answer.sort(Comparator.naturalOrder());
return answer;
}
}