Intersection of Two Arrays II Solutions in Java
Number 350
Difficulty Easy
Acceptance 51.4%
Link LeetCode
Solutions
Java solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/intersection-of-two-arrays-ii/description//// Author : liuyubobobo/// Time : 2017-11-14import java.util.HashMap;import java.util.ArrayList;/// Using Hash Map/// Time Complexity: O(len(nums1) + len(nums2)*log(len(nums1)))/// Space Complexity: O(len(nums1))public class Solution {public int[] intersect(int[] nums1, int[] nums2) {HashMap<Integer, Integer> record = new HashMap<Integer, Integer>();for(int num: nums1)if(!record.containsKey(num))record.put(num, 1);elserecord.put(num, record.get(num) + 1);ArrayList<Integer> result = new ArrayList<Integer>();for(int num: nums2)if(record.containsKey(num) && record.get(num) > 0){result.add(num);record.put(num, record.get(num) - 1);}int[] ret = new int[result.size()];int index = 0;for(Integer num: result)ret[index++] = num;return ret;}private static void printArr(int[] arr){for(int e: arr)System.out.print(e + " ");System.out.println();}public static void main(String[] args) {int[] nums1 = {1, 2, 2, 1};int[] nums2 = {2, 2};int[] res = (new Solution()).intersect(nums1, nums2);printArr(res);}}
Java solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/intersection-of-two-arrays-ii/description//// Author : liuyubobobo/// Time : 2019-04-08import java.util.Arrays;import java.util.ArrayList;/// Sorting and Two Pointers/// Time Complexity: O(nlogn)/// Space Complexity: O(1)public class Solution2 {public int[] intersect(int[] nums1, int[] nums2) {Arrays.sort(nums1);Arrays.sort(nums2);ArrayList<Integer> res = new ArrayList<>();int i = 0, j = 0;while(i < nums1.length && j < nums2.length){if(nums1[i] == nums2[j]){res.add(nums1[i]);i ++;j ++;}else if(nums1[i] < nums2[j]) i ++;else j ++;}int[] ret = new int[res.size()];int index = 0;for(Integer num: res)ret[index++] = num;return ret;}private static void printArr(int[] arr){for(int e: arr)System.out.print(e + " ");System.out.println();}public static void main(String[] args) {int[] nums1 = {1, 2, 2, 1};int[] nums2 = {2, 2};int[] res = (new Solution()).intersect(nums1, nums2);printArr(res);}}