Leetcode 349. Intersection of Two Arrays 解题报告 Python Java

来源:互联网 发布:天刀太白少女捏脸数据 编辑:程序博客网 时间:2024/05/02 04:48

1 解题思想

这道题就是说,求两个数组的交集,所以做法也很简单:
使用哈希Set存入第一个数组的值
遍历第二个数组,如果第二个的数在Set中出现,那么就是交集(与此同时,因为只能返回一个值,所以出现后还需要从Set中删除哦)

2 原题

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.

3 AC解

// 有问题可以新浪微博@MebiuWpublic class Solution {    public int[] intersection(int[] nums1, int[] nums2) {        HashSet<Integer> set = new HashSet<Integer>();        for(int i=0;i<nums1.length;i++)            set.add(nums1[i]); //遍历增加        List<Integer> resultList = new ArrayList<Integer>();        for (int i=0;i<nums2.length;i++)            if(set.contains(nums2[i])){                resultList.add(nums2[i]);                set.remove(nums2[i]); //记得删除            }        int result[] = new int[resultList.size()];        for(int i=0;i<resultList.size();i++)            result[i]=resultList.get(i);        return result;    }}

4 AC 解 Python版

感觉用Python好简洁,喵

class Solution(object):    def intersection(self, nums1, nums2):        result = list()        for num in set(nums1) :            if num in nums2:                result.append(num)        return result

5 再度更新个一句话版的

python的列表生成器,刚刚忙着赶,没用这个。。毕竟我对Python也不熟悉,只是知道有这个东西,喵

class Solution(object):    def intersection(self, nums1, nums2):        return [num for num in set(nums1) if num in nums2]
0 0