LeetCode349、350. 两个数组的交集
分析:使用集合
class Solution { public int[] intersection(int[] nums1, int[] nums2) { Set<Integer> set = new HashSet<>(); Set<Integer> set1 = new HashSet<>(); for (int num : nums1) { set1.add(num); } for (int num : nums2) { if (set1.contains(num)) { set.add(num); } } int[] res = new int[set.size()]; int index = 0; for (int n : set) { res[index ++] = n; } return res; } }
方法1:使用Map
class Solution { public int[] intersect(int[] nums1, int[] nums2) { Map<Integer,Integer> map = new HashMap<>(); for (int num : nums1) { map.put(num,map.getOrDefault(num,0) + 1); } List<Integer> list = new ArrayList<>(); for (int num : nums2) { if (map.containsKey(num)) { list.add(num); map.put(num,map.get(num) - 1); if (map.get(num) == 0) { map.remove(num); } } } int[] res = new int[list.size()]; int index = 0; for (int n : list) { res[index ++] = n; } return res; } }
方法2:排序