【题目】

找到两个数组的相同元素并输出。 

Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must be unique and you may return the result in any order.

 

Example 1:

Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2]

Example 2:

Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [9,4]
Explanation: [4,9] is also accepted.

  

【思路】

训练二分,还有很多可以优化的地方。

nums1中所有数字作为target,将它们一一和nums2数组进行比较

如果相同就加进ans集合中

 

【代码】

 

class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
        Arrays.sort(nums2);
        List<Integer> ans=new ArrayList();

        for(int i=0;i<nums1.length;i++){
            bs(nums1[i],nums2,ans);
        }
        return ans.stream().mapToInt(i->i).toArray();
    }
    
    public static void bs(int target,int[] num,List ans){
        if(ans.contains(target))
            return;//已经加入的重复数字不用再找一遍

        int left=0;int right=num.length;
        while(left<right){
            int mid=left+(right-left)/2;
            if(num[mid]==target){
                ans.add(target);
                return;
            }
            else if(num[mid]<target){
                left=mid+1;
            }
            else if(num[mid]>target){
                right=mid;
            }
        }
    }
}

 

 posted on 2021-08-18 16:45  alau  阅读(94)  评论(0编辑  收藏  举报