Intersection of Two Arrays II
2024. 9. 12. 09:23ㆍ알고리즘/Leetcode
반응형
Solution
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
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.
Explaination
public int[] intersect(int[] nums1, int[] nums2) {
Arrays.sort(nums1);
Arrays.sort(nums2);
int n = nums1.length, m = nums2.length;
int i = 0, j = 0;
List<Integer> list = new ArrayList<>();
while(i < n && j < m){
int a = nums1[i], b= nums2[j];
if(a == b){
list.add(a);
i++;
j++;
}else if(a < b){
i++;
}else{
j++;
}
}
return list.stream().mapToInt(Integer::intValue).toArray();
}
The way of solving this problem is to use two pointer interation. First the both arrays have to be sorted using Arrays.sort() methods. A List is then initialized to store the final results.
Using a while loop, I interate through both arrays nums1 and nums2. When nums1[i] < nums2[i], I need to increment j, and vice versa. Only when nums1[i] == nums2[i], the value can be stored in the list as a final result. Lastly, return an Array that is converted from the List using a stream.
반응형
'알고리즘 > Leetcode' 카테고리의 다른 글
| Move Zeroes (2) | 2024.09.23 |
|---|---|
| Plus One (2) | 2024.09.20 |
| Single Number (2) | 2024.09.05 |
| Rotate Array (3) | 2024.09.03 |
| Best Time to Buy and Sell Stock II (0) | 2024.08.31 |