[LeetCode]--349. Intersection of Two Arrays

来源:互联网 发布:c语言学会了可以干吗 编辑:程序博客网 时间:2024/06/14 17:47

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 int[] intersection(int[] nums1, int[] nums2) {        int j = 0;        int[] temp = new int[nums2.length];        List<Integer> list = new ArrayList<Integer>();        List<Integer> list2 = new ArrayList<Integer>();        for (int i = 0; i < nums1.length; i++)            list.add(nums1[i]);        for (int i = 0; i < nums2.length; i++)            if (list.contains(nums2[i]) && !list2.contains(nums2[i])) {                list2.add(nums2[i]);                temp[j++] = nums2[i];            }        int[] temp2 = new int[j];        for (int i = 0; i < temp2.length; i++) {            temp2[i] = temp[i];        }        return temp2;    }

几个小技巧自己看代码哈,反正就AC了。

0 0
原创粉丝点击