[LeetCode]--349. Intersection of Two Arrays

简介: 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

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了。

目录
相关文章
|
5月前
Leetcode 4. Median of Two Sorted Arrays
题目描述很简单,就是找到两个有序数组合并后的中位数,要求时间复杂度O(log (m+n))。 如果不要去时间复杂度,很容易就想到了归并排序,归并排序的时间复杂度是O(m+n),空间复杂度也是O(m+n),不满足题目要求,其实我开始也不知道怎么做,后来看了别人的博客才知道有个二分法求两个有序数组中第k大数的方法。
16 0
|
存储 算法
LeetCode 350. 两个数组的交集 II ntersection of Two Arrays II
LeetCode 350. 两个数组的交集 II ntersection of Two Arrays II
LeetCode 350. Intersection of Two Arrays II
给定两个数组,编写一个函数来计算它们的交集。
47 0
LeetCode 350. Intersection of Two Arrays II
|
Python
LeetCode 349. Intersection of Two Arrays
给定两个数组,编写一个函数来计算它们的交集。
51 0
LeetCode 349. Intersection of Two Arrays
Leetcode-Hard 4. Median of Two Sorted Arrays
Leetcode-Hard 4. Median of Two Sorted Arrays
77 0
|
人工智能
LeetCode之Intersection of Two Arrays
LeetCode之Intersection of Two Arrays
78 0
LeetCode 350: 两个数组的交集 II Intersection of Two Arrays II
题目: 给定两个数组,编写一个函数来计算它们的交集。 Given two arrays, write a function to compute their intersection. 示例 1: 输入: nums1 = [1,2,2,1], nums2 = [2,2] 输出: [2,2] 示例 2: 输入: nums1 = [4,9,5], nums2 = [9,4,9,8,4] 输出: [4,9] 说明: 输出结果中每个元素出现的次数,应与元素在两个数组中出现的次数一致。
696 0