349. Intersection of Two Arrays

来源:互联网 发布:颈椎牵引 知乎 编辑:程序博客网 时间:2024/06/08 11:52

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.

public class Solution {    public int[] intersection(int[] nums1, int[] nums2) {        Arrays.sort(nums1);        Arrays.sort(nums2);        ArrayList<Integer> list = new ArrayList<Integer>();        for(int i=0; i<nums1.length; i++){            if(i==0 || (i>0 && nums1[i]!=nums1[i-1])){                if(Arrays.binarySearch(nums2, nums1[i])>-1){                    list.add(nums1[i]);                }            }        }        int[] result = new int[list.size()];        int k=0;        for(int i: list){            result[k++] = i;        }        return result;    }}
原创粉丝点击