[LeetCode] 350. Intersection of Two Arrays II
Problem
Given two integer arrays nums1
and nums2
, return an array of their intersection. Each element in the result must appear as many times as it shows in both arrays and you may return the result in any order.
Example 1:
Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2,2]
Example 2:
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [4,9]
Explanation: [9,4] is also accepted.
Constraints:
1 <= nums1.length, nums2.length <= 1000
0 <= nums1[i], nums2[i] <= 1000
Follow up:
- What if the given array is already sorted? How would you optimize your algorithm?
- What if
nums1
’s size is small compared tonums2
’s size? Which algorithm is better? - What if elements of
nums2
are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?
Solution
Approach
-
배열 리스트를 선언한다.
-
각 배열의 요소가 같다면 리스트에 추가한다.
-
생성된 리스트를 배열로 변경한다.
Code
class Solution { public int[] intersect(int[] nums1, int[] nums2) { List<Integer> list = new ArrayList<>(); for (int i = 0; i < nums1.length; i++) for (int j = 0; j < nums2.length; j++) if (nums1[i] == nums2[j]) { list.add(nums1[i]); nums2[j] = -1; break; } int[] res = new int[list.size()]; for (int i = 0; i < list.size(); i++) res[i] = list.get(i); return res; } }
Time Complexity
- 배열 nums1의 길이를 q, nums2의 길이를 p라 가정할 때, 코드의 수행 시간을 지배하는 것은 중첩된 반복문의 q * p 계산 횟수이다. 따라서 본 솔루션은 O(q * p)의 시간 복잡도를 가진다.
Leave a comment