349. Intersection of Two Arrays

来源:互联网 发布:wirelessmon mac版 编辑:程序博客网 时间:2024/06/05 07:50

1.

采用两个hashset 时间复杂度为O(n);6ms;

class Solution {    public int[] intersection(int[] nums1, int[] nums2) {       //use two hashset        Set<Integer> set=new HashSet<>();        Set<Integer> interset=new HashSet<>();        for (int i=0;i<nums1.length;i++){            set.add(nums1[i]);        }        for (int i=0;i<nums2.length;i++){            if (set.contains(nums2[i])){                interset.add(nums2[i]);            }        }        int[] result=new int[interset.size()];        int i=0;        for(Integer num:interset){            result[i++]=num;        }        return result;    }}

2.

先进行排序在比较相等之后加入到set中,并转为list;O(nlogn); 5ms;

        Set<Integer> set=new HashSet<>();        Arrays.sort(nums1);        Arrays.sort(nums2);        int i=0,j=0;        while(i<nums1.length&&j<nums2.length){            if (nums1[i]<nums2[j]) i++;            else if (nums1[i]>nums2[j]) j++;            else {                set.add(nums1[i]);                i++;                j++;            }        }        int[] result=new int[set.size()];        int k=0;        for (Integer num:set){            result[k++]=num;        }        return result;

3.

排序一个list,再采用二分搜索判断相等加入到set中;O(nlogn); 9ms;

class Solution {    public int[] intersection(int[] nums1, int[] nums2) {        Set<Integer> set=new HashSet<>();        Arrays.sort(nums2);        for(Integer num:nums1){            if (binarySearch(nums2,num)) set.add(num);        }        int[] result=new int[set.size()];        int i=0;        for (Integer num:set){            result[i++]=num;        }        return result;    }    public boolean binarySearch(int[] nums, int target){        int low=0,high=nums.length-1;        while (low<=high){            int mid=low+(high-low)/2;            if (nums[mid]==target) return true;            else if (nums[mid]>target) high=mid-1;            else low=mid+1;        }        return false;    }}