@Test public void intersection() { assertEquals(2, IntersectionTwoArraysSolution.intersection(new int[]{1, 2, 1, 2}, new int[]{2, 2})[0]); assertEquals(0, IntersectionTwoArraysSolution.intersection(new int[]{}, new int[]{2, 2}).length); int[] result = IntersectionTwoArraysSolution.intersection(new int[]{1, 2, 3}, new int[]{3, 3, 1}); assertTrue(result[0] == 1 && result[1] == 3); }
static int[] intersection(int[] nums1, int[] nums2) { Set<Integer> set1 = new HashSet<>(); Set<Integer> set2 = new HashSet<>(); for (int i : nums1) { set1.add(i); } for (int i : nums2) { if (set1.contains(i)) set2.add(i); } int len = set2.size(); int[] result = new int[len]; if (len == 0) return result; Iterator<Integer> iter = set2.iterator(); for (int i = 0; i < len; i++) { result[i] = iter.next(); } return result; }
IntersectionTwoArraysSolution { static int[] intersection(int[] nums1, int[] nums2) { Set<Integer> set1 = new HashSet<>(); Set<Integer> set2 = new HashSet<>(); for (int i : nums1) { set1.add(i); } for (int i : nums2) { if (set1.contains(i)) set2.add(i); } int len = set2.size(); int[] result = new int[len]; if (len == 0) return result; Iterator<Integer> iter = set2.iterator(); for (int i = 0; i < len; i++) { result[i] = iter.next(); } return result; } }
IntersectionTwoArraysSolution { static int[] intersection(int[] nums1, int[] nums2) { Set<Integer> set1 = new HashSet<>(); Set<Integer> set2 = new HashSet<>(); for (int i : nums1) { set1.add(i); } for (int i : nums2) { if (set1.contains(i)) set2.add(i); } int len = set2.size(); int[] result = new int[len]; if (len == 0) return result; Iterator<Integer> iter = set2.iterator(); for (int i = 0; i < len; i++) { result[i] = iter.next(); } return result; }  }
IntersectionTwoArraysSolution { static int[] intersection(int[] nums1, int[] nums2) { Set<Integer> set1 = new HashSet<>(); Set<Integer> set2 = new HashSet<>(); for (int i : nums1) { set1.add(i); } for (int i : nums2) { if (set1.contains(i)) set2.add(i); } int len = set2.size(); int[] result = new int[len]; if (len == 0) return result; Iterator<Integer> iter = set2.iterator(); for (int i = 0; i < len; i++) { result[i] = iter.next(); } return result; }   }
IntersectionTwoArraysSolution { static int[] intersection(int[] nums1, int[] nums2) { Set<Integer> set1 = new HashSet<>(); Set<Integer> set2 = new HashSet<>(); for (int i : nums1) { set1.add(i); } for (int i : nums2) { if (set1.contains(i)) set2.add(i); } int len = set2.size(); int[] result = new int[len]; if (len == 0) return result; Iterator<Integer> iter = set2.iterator(); for (int i = 0; i < len; i++) { result[i] = iter.next(); } return result; }    }