package com.example.lettcode.dailyexercises;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @Class Intersect
* @Description 350 两个数组的交集II
* 给定两个数组,编写一个函数来计算它们的交集。
* <p>
* 示例 1:
* 输入: nums1 = [1,2,2,1], nums2 = [2,2]
* 输出: [2,2]
* <p>
* 示例 2:
* 输入: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
* 输出: [4,9]
* <p>
* 说明:
* 我们可以不考虑输出结果的顺序。
* @Author
* @Date 2020/7/13
**/
public class Intersect {
}
/**
* 解法1:利用hash
*/
public static int[] intersect(int[] nums1, int[] nums2) {
if (nums1 == null || nums1.length == 0
|| nums2 == null || nums2.length == 0) return new int[]{};
List<Integer> ans = new ArrayList<>();
Map<Integer, Integer> integerMap = new HashMap<>();
for (int num : nums1) {
if (integerMap.containsKey(num)) {
int count = integerMap.get(num);
count++;
integerMap.put(num, count);
} else {
integerMap.put(num, 1);
}
}
for (int num : nums2) {
if (integerMap.containsKey(num)) {
ans.add(num);
int count = integerMap.get(num);
count--;
if (count == 0) {
integerMap.remove(num);
continue;
}
integerMap.put(num, count);
}
}
return ans.stream().mapToInt(Integer::valueOf).toArray();
}
/**
* 解法2:利用排序,时间复杂度为O(NlgN)
*/
public static int[] intersect(int[] nums1, int[] nums2) {
if (nums1 == null || nums1.length == 0
|| nums2 == null || nums2.length == 0) return new int[]{};
quickSort(nums1, 0, nums1.length - 1);
quickSort(nums2, 0, nums2.length - 1);
int p = 0, q = 0;
List<Integer> integerList = new ArrayList<>();
while (p < nums1.length && q < nums2.length) {
if (nums1[p] > nums2[q]) q++;
else if (nums1[p] < nums2[q]) p++;
else {
integerList.add(nums1[p]);
p++;
q++;
}
}
return integerList.stream().mapToInt(Integer::valueOf).toArray();
}
public static void quickSort(int[] num, int start, int end) {
if (num == null || num.length <= 1) return;
if (start > end) return;
int temp = num[start];
int p = start, q = end;
while (p < q) {
while (p < q && temp <= num[q]) q--;
while (p < q && temp >= num[p]) p++;
if (p < q) {
num[p] += num[q];
num[q] = num[p] - num[q];
num[p] = num[p] - num[q];
}
}
num[start] = num[p];
num[p] = temp;
quickSort(num, start, p - 1);
quickSort(num, p + 1, end);
}
// 测试用例
public static void main(String[] args) {
int[] num1 = new int[]{1, 2, 2, 1};
int[] num2 = new int[]{2, 2};
int[] ans = intersect(num1, num2);
System.out.println("Intersect result demo01:");
for (int num : ans) {
System.out.print("," + num);
}
System.out.println("");
num1 = new int[]{4, 9, 5};
num2 = new int[]{9, 4, 9, 8, 4};
ans = intersect(num1, num2);
System.out.println("Intersect result demo02:");
for (int num : ans) {
System.out.print("," + num);
}
System.out.println("");
}
leetcode 349: 两个数组的交集https://www.cnblogs.com/fyusac/p/13913356.html