Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // https://leetcode.com/problems/intersection-of-two-arrays/
- /* Runtime: 0 ms, faster than 100.00% of Java online submissions for Intersection of Two Arrays.
- Memory Usage: 37.6 MB, less than 58.11% of Java online submissions for Intersection of Two Arrays. */
- private static class UsingArray implements Solution {
- public int[] intersection(int[] nums1, int[] nums2) {
- if (nums1.length < nums2.length) {
- int[] swap = nums1; nums1 = nums2; nums2 = swap;
- }
- boolean[] uniques = new boolean[1024];
- for (int num : nums2) uniques[num] = true;
- int index = -1;
- int[] ans = new int[nums2.length];
- for (int num : nums1) {
- if (uniques[num]) {
- uniques[num] = false;
- ans[++index] = num;
- }
- }
- return Arrays.copyOfRange(ans, 0, index + 1);
- }
- }
- /* Runtime: 1 ms, faster than 99.85% of Java online submissions for Intersection of Two Arrays.
- Memory Usage: 37.6 MB, less than 58.11% of Java online submissions for Intersection of Two Arrays. */
- private static class UsingBitSet implements Solution {
- public int[] intersection(int[] nums1, int[] nums2) {
- if (nums1.length < nums2.length) {
- int[] swap = nums1; nums1 = nums2; nums2 = swap;
- }
- BitSet uniques = new BitSet(256);
- for (int num : nums2) uniques.set(num);
- int index = -1;
- int[] ans = new int[nums2.length];
- for (int num : nums1) {
- if (uniques.get(num)) {
- uniques.clear(num);
- ans[++index] = num;
- }
- }
- return Arrays.copyOfRange(ans, 0, index + 1);
- }
- }
- /* Runtime: 2 ms, faster than 97.92% of Java online submissions for Intersection of Two Arrays.
- Memory Usage: 36.9 MB, less than 89.19% of Java online submissions for Intersection of Two Arrays. */
- private static class UsingHashSet implements Solution {
- public int[] intersection(int[] nums1, int[] nums2) {
- if (nums1.length < nums2.length) {
- int[] swap = nums1; nums1 = nums2; nums2 = swap;
- }
- HashSet<Integer> uniques = new HashSet<>();
- for (int num : nums2) uniques.add(num);
- int index = -1;
- int[] ans = new int[uniques.size()];
- for (int num : nums1) {
- if (uniques.contains(num)) {
- uniques.remove(num);
- ans[++index] = num;
- }
- }
- return Arrays.copyOfRange(ans, 0, index + 1);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement