Intersection of Two Arrays II (E)
題目
Given two arrays, write a function to compute their intersection.
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]
Note:
- Each element in the result should appear as many times as it shows in both arrays.
- The result can be in any order.
Follow up:
- What if the given array is already sorted? How would you optimize your algorithm?
- What if nums1's size is small compared to nums2'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?
題意
取兩陣列的交集,包含所有重復元素
思路
普通做法直接用HashMap處理即可,
排序情況下用類似于歸并排序的方法處理,
代碼實作
Java
Hash
class Solution {
public int[] intersect(int[] nums1, int[] nums2) {
List<Integer> list = new ArrayList<>();
Map<Integer, Integer> record = new HashMap<>();
for (int num : nums1) {
record.putIfAbsent(num, 0);
record.put(num, record.get(num) + 1);
}
for (int num : nums2) {
if (record.containsKey(num) && record.get(num) > 0) {
list.add(num);
record.put(num, record.get(num) - 1);
}
}
int[] res = new int[list.size()];
int i = 0;
for (int num : list) {
res[i++] = num;
}
return res;
}
}
排序
class Solution {
public int[] intersect(int[] nums1, int[] nums2) {
List<Integer> list = new ArrayList<>();
Arrays.sort(nums1);
Arrays.sort(nums2);
int p1 = 0, p2 = 0;
while (p1 < nums1.length && p2 < nums2.length) {
if (nums1[p1] > nums2[p2]) {
p2++;
} else if (nums1[p1] < nums2[p2]) {
p1++;
} else {
list.add(nums1[p1]);
p1++;
p2++;
}
}
int[] res = new int[list.size()];
int i = 0;
for (int num : list) {
res[i++] = num;
}
return res;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/33840.html
標籤:其他
