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

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

Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2].

Challenge

Can you implement it in three different algorithms?

解法一:

 class Solution {
public:
/**
* @param nums1 an integer array
* @param nums2 an integer array
* @return an integer array
*/
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
sort(nums1.begin(), nums1.end());
sort(nums2.begin(), nums2.end()); vector<int> intersect;
vector<int>::iterator it1 = nums1.begin(), it2 = nums2.begin();
while ((it1 != nums1.end()) && (it2 != nums2.end())) {
if (*it1 < *it2) {
it1++;
} else if (*it1 > *it2) {
it2++;
} else {
intersect.push_back(*it1);
it1++; it2++;
}
} auto last = unique(intersect.begin(), intersect.end());
intersect.erase(last, intersect.end());
return intersect;
}
};

sort & merge

类属性算法unique的作用是从输入序列中“删除”所有相邻的重复元素。该算法删除相邻的重复元素,然后重新排列输入范围内的元素,并且返回一个迭代器(容器的长度没变,只是元素顺序改变了),表示无重复的值范围得结束。在STL中unique函数是一个去重函数, unique的功能是去除相邻的重复元素(只保留一个),其实它并不真正把重复的元素删除,是把重复的元素移到后面去了,然后依然保存到了原数组中,然后 返回去重后最后一个元素的地址,因为unique去除的是相邻的重复元素,所以一般用之前都会要排一下序。

常见的用法如下:

 /*
* sort words alphabetically so we can find the duplicates
*/
sort(words.begin(), words.end()); /* eliminate duplicate words:
* unique reorders words so that each word appears once in the
* front portion of words and returns an iterator one past the unique range;
* erase uses a vector operation to remove the nonunique elements
*/
vector<string>::iterator end_unique = unique(words.begin(), words.end()); words.erase(end_unique, words.end());

参考@NineChapter的代码

解法二:

 public class Solution {
/**
* @param nums1 an integer array
* @param nums2 an integer array
* @return an integer array
*/
public int[] intersection(int[] nums1, int[] nums2) {
Arrays.sort(nums1);
Arrays.sort(nums2); int i = 0, j = 0;
int[] temp = new int[nums1.length];
int index = 0;
while (i < nums1.length && j < nums2.length) {
if (nums1[i] == nums2[j]) {
if (index == 0 || temp[index - 1] != nums1[i]) {
temp[index++] = nums1[i];
}
i++;
j++;
} else if (nums1[i] < nums2[j]) {
i++;
} else {
j++;
}
} int[] result = new int[index];
for (int k = 0; k < index; k++) {
result[k] = temp[k];
} return result;
}
}

sort & merge

参考@NineChapter的代码

解法三:

 public class Solution {
/**
* @param nums1 an integer array
* @param nums2 an integer array
* @return an integer array
*/
public int[] intersection(int[] nums1, int[] nums2) {
if (nums1 == null || nums2 == null) {
return null;
} HashSet<Integer> hash = new HashSet<>();
for (int i = 0; i < nums1.length; i++) {
hash.add(nums1[i]);
} HashSet<Integer> resultHash = new HashSet<>();
for (int i = 0; i < nums2.length; i++) {
if (hash.contains(nums2[i]) && !resultHash.contains(nums2[i])) {
resultHash.add(nums2[i]);
}
} int size = resultHash.size();
int[] result = new int[size];
int index = 0;
for (Integer num : resultHash) {
result[index++] = num;
} return result;
}
}

hash map

参考@NineChapter的代码

解法四:

 public class Solution {
/**
* @param nums1 an integer array
* @param nums2 an integer array
* @return an integer array
*/
public int[] intersection(int[] nums1, int[] nums2) {
if (nums1 == null || nums2 == null) {
return null;
} HashSet<Integer> set = new HashSet<>(); Arrays.sort(nums1);
for (int i = 0; i < nums2.length; i++) {
if (set.contains(nums2[i])) {
continue;
}
if (binarySearch(nums1, nums2[i])) {
set.add(nums2[i]);
}
} int[] result = new int[set.size()];
int index = 0;
for (Integer num : set) {
result[index++] = num;
} return result;
} private boolean binarySearch(int[] nums, int target) {
if (nums == null || nums.length == 0) {
return false;
} int start = 0, end = nums.length - 1;
while (start + 1 < end) {
int mid = (end - start) / 2 + start;
if (nums[mid] == target) {
return true;
}
if (nums[mid] < target) {
start = mid;
} else {
end = mid;
}
} if (nums[start] == target) {
return true;
}
if (nums[end] == target) {
return true;
} return false;
}
}

sort & binary search

参考@NineChapter的代码

解法五:

 public class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
// Write your code here
HashSet<Integer> set1 = new HashSet<>();
ArrayList<Integer> result = new ArrayList<>();
for(int n1 : nums1){
set1.add(n1);
}
for(int n2 : nums2){
if(set1.contains(n2)){
result.add(n2);
set1.remove(n2);
}
}
int[] ret = new int[result.size()];
for(int i = 0; i < result.size(); i++){
ret[i] = result.get(i);
}
return ret;
}
};

参考@NineChapter的代码

547. Intersection of Two Arrays【easy】的更多相关文章

  1. 160. Intersection of Two Linked Lists【easy】

    160. Intersection of Two Linked Lists[easy] Write a program to find the node at which the intersecti ...

  2. 88. Merge Sorted Array【easy】

    88. Merge Sorted Array[easy] Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 ...

  3. 217. Contains Duplicate【easy】

    217. Contains Duplicate[easy] Given an array of integers, find if the array contains any duplicates. ...

  4. 170. Two Sum III - Data structure design【easy】

    170. Two Sum III - Data structure design[easy] Design and implement a TwoSum class. It should suppor ...

  5. 206. Reverse Linked List【easy】

    206. Reverse Linked List[easy] Reverse a singly linked list. Hint: A linked list can be reversed eit ...

  6. 203. Remove Linked List Elements【easy】

    203. Remove Linked List Elements[easy] Remove all elements from a linked list of integers that have ...

  7. 83. Remove Duplicates from Sorted List【easy】

    83. Remove Duplicates from Sorted List[easy] Given a sorted linked list, delete all duplicates such ...

  8. 21. Merge Two Sorted Lists【easy】

    21. Merge Two Sorted Lists[easy] Merge two sorted linked lists and return it as a new list. The new ...

  9. 142. Linked List Cycle II【easy】

    142. Linked List Cycle II[easy] Given a linked list, return the node where the cycle begins. If ther ...

随机推荐

  1. 【mybatis】mybatis自定义动态字段查询,mybatis实现动态字段查询,如果某个条件为null,则不查询某个字段,否则就查询某个字段

    mybatis实现动态字段查询,如果某个条件为null,则不查询某个字段,否则就查询某个字段 先看一下 怎么实现动态的自定义字段查询: 例如: 而field 就是数据表中的某一个字段 String f ...

  2. nodejs调试利器:supervisor

    测试多了,是不是感觉每次要重新node一次app.js,很烦恼? 用supervisor,只有有改动,页面刷新就可以看到效果,不用重启node.js 安装: npm -g install superv ...

  3. nginx配置rewrite总结

    1.rewrite regex replacement [flag] 2.flag为break时,url重写后,直接使用当前资源,不在执行location里其他语句,完成本次请求,地址栏url不变. ...

  4. git命令01

    1.了解git工具产生的背景知识.git 是什么? 目前它是一种分布式版本控制系统.那什么又是版本控制系统? 一种能自动帮助记录每次文件的改动,不仅仅是记录自己对文件的修 改变化,而且可以记录其他人对 ...

  5. 30分钟LINQ教程【转】

    千万别被这个页面的滚动条吓到!!! 我相信你一定能在30分钟之内看完它!!! 在说LINQ之前必须先说说几个重要的C#语言特性 一:与LINQ有关的语言特性 1.隐式类型 (1)源起 在隐式类型出现之 ...

  6. lumisoft邮件内容中文乱码问题

    修改MIME_b_Text.cs文件,红色字体为添加的部分,绿色为修改部分 private static Encoding m_pEncoding = Encoding.Default; #regio ...

  7. scrapy-splash抓取动态数据例子二

    一.介绍 本例子用scrapy-splash抓取一点资讯网站给定关键字抓取咨询信息. 给定关键字:打通:融合:电视 抓取信息内如下: 1.资讯标题 2.资讯链接 3.资讯时间 4.资讯来源 二.网站信 ...

  8. 一个故事讲清NIO

    假设某银行只有10个职员.该银行的业务流程分为以下4个步骤: 1) 顾客填申请表(5分钟): 2) 职员审核(1分钟): 3) 职员叫保安去金库取钱(3分钟): 4) 职员打印票据,并将钱和票据返回给 ...

  9. BST数据结构题

    给定BST.改动BST,使得每一个点都是大于他的结点的值之和 关键是这题递归參数怎么设计,每一个点比他大的有两快.一个是右子书(假设有的话),还有一个是祖先里面比他大的,假设直接用这两个的话,找不到递 ...

  10. [Functional Programming ADT] Combine Multiple State ADT Based Redux Reducers

    Redux provides a convenient helper for combining many reducers called combineReducer, but it focuses ...