[LeetCode]349. Intersection of Two Arrays

来源:互联网 发布:袖剑 淘宝 编辑:程序博客网 时间:2024/06/06 05:58

Binary Search很简单的一道题,但是犯了好多错误。

要求:再从头写一遍,要求一次bug-free AC.

https://leetcode.com/problems/intersection-of-two-arrays/description/


Given two arrays, write a function to compute their intersection.

Example:
Given nums1 = [1, 2, 2, 1]nums2 = [2, 2], return [2].

Note:

  • Each element in the result must be unique.
  • The result can be in any order.

1.Binary Search

public class Solution {    public int[] intersection(int[] nums1, int[] nums2) {        if(nums1==null || nums2==null || nums1.length<1 || nums2.length<1)            return new int[0];                List<Integer> list = new ArrayList<>();        Arrays.sort(nums2);                        for(int i=0; i<nums1.length; i++){            if(list.contains(nums1[i])) continue;                        int low=0, high=nums2.length-1;            int mid=(high-low)/2+low;            boolean find=false;            while(low<=high){                if(nums2[mid]==nums1[i])                {find=true;break;}                else if(nums2[mid]>nums1[i])                    high=mid-1;                else low=mid+1;                mid=(high-low)/2+low;            }                        if(find) list.add(nums2[mid]);        }                int n=list.size();        int[] res=new int[n];        for(int i=0; i<n; i++)            res[i]=list.get(i);                return res;    }}

while(low<=high)

high=mid-1;

low=mid+1;

以及还犯的错误有,直接令low=nums2[0], high=nums2[n-1];

总之今天不大正常。

还有,do{}while();后面要加分号


2、HashSet

public class Solution {    public int[] intersection(int[] nums1, int[] nums2) {        Set<Integer> set = new HashSet<>();        Set<Integer> intersect = 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])) {                intersect.add(nums2[i]);            }        }        int[] result = new int[intersect.size()];        int i = 0;        for (Integer num : intersect) {            result[i++] = num;        }        return result;    }}


3、Sort both arrays, use two pointers

public class Solution {    public int[] intersection(int[] nums1, int[] nums2) {        Set<Integer> set = new HashSet<>();        Arrays.sort(nums1);        Arrays.sort(nums2);        int i = 0;        int 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;    }}



原创粉丝点击