Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // https://leetcode.com/problems/intersection-of-two-arrays/
- /* Runtime: 1 ms, faster than 99.85% of Java online submissions for Intersection of Two Arrays.
- Memory Usage: 37.2 MB, less than 89.19% 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;
- }
- int length = 0;
- boolean[] uniques = new boolean[1024], set2 = new boolean[1024];
- for (int num : nums2) set2[num] = true;
- for (int num : nums1) {
- if (set2[num] && !uniques[num]) {
- uniques[num] = true;
- ++length;
- }
- }
- int index = -1;
- int[] ans = new int[length];
- for (int i = 0; i < uniques.length; i++) {
- if (uniques[i]) {
- ans[++index] = i;
- }
- }
- return ans;
- }
- }
- /* 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), set2 = new BitSet(256);
- for (int num : nums2) set2.set(num);
- int index = -1;
- int[] ans = new int[nums2.length];
- for (int num : nums1) {
- if (set2.get(num) && !uniques.get(num)) {
- uniques.set(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> set2 = new HashSet<>();
- for (int num : nums2) set2.add(num);
- HashSet<Integer> uniques = new HashSet<>();
- int index = -1;
- int[] ans = new int[set2.size()];
- for (int num : nums1) {
- if (set2.contains(num) && uniques.add(num))
- ans[++index] = num;
- }
- return Arrays.copyOfRange(ans, 0, index + 1);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement