leetcode[Intersection of Two Arrays]

来源:互联网 发布:mac 移动硬盘 ntfs 编辑:程序博客网 时间:2024/05/29 02:19

[Intersection of Two Arrays II]的解法也可以适用于这里,只不过对结果的处理一个是set一个是list

解法一:

public class Solution {    public int[] intersection(int[] nums1, int[] nums2) {    //既然是求交集,那么结果集合中就没有重复元素,先用Set来存    HashSet<Integer> set = new HashSet<>();    Arrays.sort(nums1);    Arrays.sort(nums2);    int begin = 0;//begin用来定位nums2的数组,防止找重了    for(int i = 0; i < nums1.length; i++){    for(int j = begin; j < nums2.length; j++){    if(nums1[i] == nums2[j]){    set.add(nums1[i]);    begin++;//因为先将nums1和nums2排序了    }    }    }    /*Integer[] temp = set.toArray(new Integer[set.size()]);    int[] res = new int[](temp);*/        //上面想要将set转换为int[]数组,但是涉及到一堆泛型,泛型与基本类型又矛盾,自己写    int[] res = new int[set.size()];//知道set的size就可以了    int put = 0;    for(int t : set){    res[put++] = t;    }    return res;    }}


解法二:

public class Solution {    public int[] intersection(int[] nums1, int[] nums2) {        LinkedList<Integer> list = new LinkedList<>();        for(int i = 0; i < nums1.length; i++){//List采用contains这个接口,先转换为list        list.add(nums1[i]);        }        HashSet<Integer> temp = new HashSet<>();//要去重,所以用set存                for(int i = 0; i < nums2.length; i++){        if(list.contains(nums2[i])){        temp.add(nums2[i]);        //list.remove(nums2[i]);//原来nums1对应的list删除这个元素        list.remove(new Integer(nums2[i]));//这里有个重载,若remove参数是int,代表下标,integer才代表对象        }        }                int[] res = new int[temp.size()];        int put = 0;        for(int t : temp){        res[put++] = t;        }        return res;    }}

解法三(对解法一的优化,思路更清晰):

public class Solution {public int binarySearch(int[] nums, int x){int low = 0, high = nums.length - 1;int mid = (low + high) / 2;while(low <= high){mid = (low + high) / 2;//二分查找在循环体内要修改mid!!if(x == nums[mid]){return mid;}else if(x < nums[mid]){high = mid - 1;}else{low = mid + 1;}//System.out.println(low + " : " + high + "  " + x);}return -1;}    public int[] intersection(int[] nums1, int[] nums2) {    //求交集:思路是查找nums2中和nums1中相同的元素,涉及到查找,那么就先排序,用二分查找    Arrays.sort(nums2);        HashSet<Integer> set = new HashSet<>();    //从nums1中开始查找    for(int i = 0; i < nums1.length; i++){    if(binarySearch(nums2, nums1[i]) != -1){    set.add(nums1[i]);//找到就插入    }    //System.out.println("...");    }        int[] res = new int[set.size()];    int put = 0;    for(int t : set){    res[put++] = t;    }        return res;    }}


原创粉丝点击