博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
349. Intersection of Two Arrays - Easy
阅读量:7222 次
发布时间:2019-06-29

本文共 2588 字,大约阅读时间需要 8 分钟。

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

Example 1:

Input: nums1 = [1,2,2,1], nums2 = [2,2]Output: [2]

Example 2:

Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]Output: [9,4]

Note:

  • Each element in the result must be unique.
  • The result can be in any order.

 

M1: binary search

先把nums2排序,然后对于nums1中的每一个元素,在nums2中进行binary search,需要一个set存结果

time: O(nlogn), space: O(1)

class Solution {    public int[] intersection(int[] nums1, int[] nums2) {        Set
set = new HashSet<>(); Arrays.sort(nums2); for(int n : nums1) { if(binarySearch(nums2, n)) { set.add(n); } } int[] res = new int[set.size()]; int i = 0; for(int n : set) { res[i++] = n; } return res; } public boolean binarySearch(int[] nums, int target) { int left = 0, right = nums.length - 1; while(left <= right) { int mid = left + (right - left) / 2; if(nums[mid] == target) { return true; } else if(nums[mid] > target) { right = mid - 1; } else { left = mid + 1; } } return false; }}

 

 

M2: hash table

用两个set,先把nums1元素放进set1,如果nums2中也有该元素,放进res set里

time: O(n), space: O(n)

class Solution {    public int[] intersection(int[] nums1, int[] nums2) {        Set
set1 = new HashSet<>(); Set
set2 = new HashSet<>(); for(int n : nums1) { set1.add(n); } for(int n : nums2) { if(set1.contains(n)) { set2.add(n); } } int[] res = new int[set2.size()]; int i = 0; for(int n : set2) { res[i++] = n; } return res; }}

 

M3: two pointers

需要先对两个数组都排序,并用set存结果去重

time: O(nlogn), space: O(1)

class Solution {    public int[] intersection(int[] nums1, int[] nums2) {        Set
set = new HashSet<>(); Arrays.sort(nums1); Arrays.sort(nums2); int i = 0, j = 0; while(i < nums1.length && j < nums2.length) { if(nums1[i] == nums2[j]) { set.add(nums1[i]); i++; j++; } else if(nums1[i] > nums2[j]) { j++; } else { i++; } } int[] res = new int[set.size()]; int k = 0; for(int n : set) { res[k++] = n; } return res; }}

 

转载于:https://www.cnblogs.com/fatttcat/p/10229425.html

你可能感兴趣的文章
SQL中ON和WHERE的区别
查看>>
[Algorithms] Solve Complex Problems in JavaScript with Dynamic Programming
查看>>
MetaModelEngine:约束和验证
查看>>
ASP.NET运行时错误
查看>>
acdream 1014 Dice Dice Dice(组合)
查看>>
javascript异步编程系列【七】----扫盲,我们为什么要用Jscex
查看>>
WindowsServer2003+IIS6+ASP+NET+PHP+MSSQL+MYSQL配置说明 |备份于waw.cnblogs.com
查看>>
MVC中几种常用ActionResult
查看>>
[转]Linux下实用的查看内存和多核CPU状态命令
查看>>
【踩坑记】从HybridApp到ReactNative
查看>>
maven全局配置文件settings.xml详解
查看>>
23种设计模式之状态模式(State)
查看>>
【Android小项目】找不同,改编自&quot;寻找房祖名&quot;的一款开源小应用。
查看>>
jquery文档操作
查看>>
用keras做SQL注入攻击的判断
查看>>
JS判断图片加载完成方法
查看>>
window.print ()
查看>>
【玩转Ubuntu】01. Ubuntu上配置JDK
查看>>
Leetcode: Path Sum
查看>>
我为什么放弃Go语言
查看>>