兩個數組的交集1
題目:
For Example:
示例 1:
輸入:nums1 = [1,2,2,1], nums2 = [2,2]
輸出:[2]
示例 2:
輸入:nums1 = [4,9,5], nums2 = [9,4,9,8,4]
輸出:[9,4]
Solution:
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Set<Integer> intersect = new HashSet<Integer>();
int len1 = nums1.length;
int len2 = nums2.length;
Set<Integer> set = new HashSet<Integer>();
if(len1 < len2){
for (int i = 0; i < len2; i++) {
if (!set.contains(nums2[i])) {
set.add(nums2[i]);
}
}
for (int j = 0; j < len1; j++) {
if (set.contains(nums1[j])) {
intersect.add(nums1[j]);
}
}
} else {
for (int i = 0; i < len1; i++) {
if (!set.contains(nums1[i])) {
set.add(nums1[i]);
}
}
for (int j = 0; j < len2; j++) {
if (set.contains(nums2[j])) {
intersect.add(nums2[j]);
}
}
}
int[] array = new int[intersect.size()];
int i = 0;
for(int value:intersect) {
array[i++] = value;
}
return array;
兩個數組的交集2
題目:
For Example:
示例 1:
輸入:nums1 = [1,2,2,1], nums2 = [2,2]
輸出:[2,2]
示例 2:
輸入:nums1 = [4,9,5], nums2 = [9,4,9,8,4]
輸出:[4,9]
Solution:
class Solution {
public int[] intersect(int[] nums1, int[] nums2) {
// 先找出比較長的數組
if (nums1.length < nums2.length){
return intersect(nums2, nums1);
}
// 存放值與出現的次數
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
//周遊數組,初始化 map
for (int i = 0; i < nums1.length; i++) {
map.put(nums1[i], map.getOrDefault(nums1[i], 0) + 1);
}
int[] array = new int[nums1.length];
int index = 0;
for (int j = 0; j < nums2.length; j++) {
if (map.containsKey(nums2[j])){
array[index++] = nums2[j];
if ((map.get(nums2[j]) - 1) <= 0){
map.remove(nums2[j]);
} else {
map.put(nums2[j], map.get(nums2[j]) - 1);
}
}
}
int arr2[] = java.util.Arrays.copyOf(array,index);
return