数据结构笔记总结(6.9)Leetcode上更多集合和映射的问题

数据结构笔记总结(6.9)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 result can be in any order.

简单翻译一下:
给定两个数组,写一个函数来计算他们的交集
例子:
给定 nums1 = [1, 2, 2, 1], nums2 = [2, 2],返回 [2]
提示:

  • 每个在结果中的元素必定是唯一的
  • 我们可以不考虑输出结果的顺序

使用集合来解答

import java.util.ArrayList;
import java.util.TreeSet;

class Solution {
    public int[] intersection(int[] nums1, int[] nums2) {

        TreeSet set = new TreeSet<>();
        for(int num: nums1)
            set.add(num);

        ArrayList list = new ArrayList<>();
        for(int 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;
    }
}

350. Intersection of Two Arrays II

Given two arrays, write a function to compute their intersection.

Example:
Given nums1 = [1, 2, 2, 1], nums2 =[2, 2], return[2, 2]

Note:
Each element in the result should appear as many times as it shows in both arrays.
The result can be in any order.
Follow up:
What if the given array is already sorted? How would you optimize your algorithm?
What if nums1's size is small compared to nums2's size? Which algorithm is better?
What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?

给定两个数组,写一个方法来计算它们的交集。

例如:
给定 nums1 = [1, 2, 2, 1], nums2 = [2, 2], 返回 [2, 2].

注意:

  1. 输出结果中每个元素出现的次数,应与元素在两个数组中出现的次数一致。
  2. 我们可以不考虑输出结果的顺序。

跟进:

  1. 如果给定的数组已经排好序呢?你将如何优化你的算法?
  2. 如果 nums1 的大小比 nums2 小很多,哪种方法更优?
  3. 如果nums2的元素存储在磁盘上,内存是有限的,你不能一次加载所有的元素到内存中,你该怎么办?

使用映射来解答

import java.util.ArrayList;
import java.util.TreeMap;

public class Solution {

    public int[] intersect(int[] nums1, int[] nums2) {

        TreeMap map = new TreeMap<>();
        for(int num: nums1){
            if(!map.containsKey(num))
                map.put(num, 1);
            else
                map.put(num, map.get(num) + 1);
        }

        ArrayList res = new ArrayList<>();
        for(int num: nums2){
            if(map.containsKey(num)){
                res.add(num);
                map.put(num, map.get(num) - 1);
                if(map.get(num) == 0)
                    map.remove(num);
            }
        }

        int[] ret = new int[res.size()];
        for(int i = 0 ; i < res.size() ; i ++)
            ret[i] = res.get(i);

        return ret;
    }
}

源码下载

[dm href='https://www.jikewenku.com/product/1487.html']下载地址[/dm]

导航目录

[dm href='https://www.jikewenku.com/geeknote/2241.html']查看导航[/dm]

本站所有文章均来自互联网,如有侵权,请联系站长删除。极客文库 » 数据结构笔记总结(6.9)Leetcode上更多集合和映射的问题
分享到:
赞(0)

评论抢沙发

评论前必须登录!