publicint[] intersection(int[] nums1, int[] nums2) { Set<Integer> interSet = newHashSet<>(); // use hash set to avoid duplicates Set<Integer> set = newHashSet<>(); // add nums1 to set for (int val : nums1) set.add(val); // check if nums2 in set for (int val : nums2) { if (set.contains(val)) { interSet.add(val); } } // to array int[] result = newint[interSet.size()]; intcount=0; for (int val : interSet) { result[count] = val; ++count; } return result; }
publicint[] intersection(int[] nums1, int[] nums2) { // Assume they are sorted Arrays.sort(nums1); Arrays.sort(nums2); Set<Integer> result = newHashSet<>(); intn1= nums1.length, n2 = nums2.length; inti1=0, i2 = 0; while (i1 < n1 && i2 < n2) { while (i1 < n1 && i2 < n2 && nums1[i1] < nums2[i2]) ++i1; while (i1 < n1 && i2 < n2 && nums1[i1] > nums2[i2]) ++i2; // critical: consider nums1[i1] < nums2[i2] --> if it is, we should continue to the next loop if (i1 < n1 && i2 < n2 && nums1[i1] == nums2[i2]) { result.add(nums1[i1]); // we use hash set --> no need to handle duplicates ++i1; ++i2; // update indices should be inside the if logic } } int[] output = newint[result.size()]; inti=0; for (int val : result) { output[i] = val; ++i; } return output; }