LeetCode349.两个数组的交集(Java实现)

链接:https://leetcode-cn.com/problems/intersection-of-two-arrays/

class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {
         TreeSet set=new TreeSet();
        for (Integer num : nums1) {
			set.add(num);//1 2
		}
        ArrayList list=new ArrayList();
        for(Integer num:nums2){
        	if(set.contains(num)){
        		list.add(num);
        		set.remove(num);
        	}
        }
        int[] res=new int[list.size()];
        for (int i = 0; i < list.size(); i++) {
			res[i]=list.get(i);
		}
        return res;
    }
}

 

你可能感兴趣的:(LeetCode编程题)