547. Intersection of Two Arrays【easy】
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.
Given nums1 = [1, 2, 2, 1]
, nums2 = [2, 2]
, return [2]
.
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】的更多相关文章
- 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 ...
- 88. Merge Sorted Array【easy】
88. Merge Sorted Array[easy] Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 ...
- 217. Contains Duplicate【easy】
217. Contains Duplicate[easy] Given an array of integers, find if the array contains any duplicates. ...
- 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 ...
- 206. Reverse Linked List【easy】
206. Reverse Linked List[easy] Reverse a singly linked list. Hint: A linked list can be reversed eit ...
- 203. Remove Linked List Elements【easy】
203. Remove Linked List Elements[easy] Remove all elements from a linked list of integers that have ...
- 83. Remove Duplicates from Sorted List【easy】
83. Remove Duplicates from Sorted List[easy] Given a sorted linked list, delete all duplicates such ...
- 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 ...
- 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 ...
随机推荐
- 统计中的t检验
1.什么情况下,应用t检验 1. 已知总体的均值m,或者我们假设了一个总体均值m: 2. 我们知道样本的个数n,样本的的方差var,样本的均值m: 3. 我们假设总体,或者样本都是服从正太分布的. 2 ...
- 新公司官网项目优化实践(Vue)
入职后接手website-html和website-mobile项目,发现项目加载速度不太理想,于是结合自己之前的经验对项目做了优化.此篇文章主要记录这次优化详情. 原始项目:开发环境:website ...
- minishift的本地代码构建
看文档说支持,但实际尝试了下,失败 发现仍然是找github中的代码 找了半天,发现是在目录下有.git的隐含目录,然后copy到其他目录下删除,然后再试,发现仍然失败. 日志看是指定的目录并没有传入 ...
- TensorFlow进阶(三)---变量的创建、初始化
变量的的创建.初始化.保存和加载 其实变量的作用在语言中相当,都有存储一些临时值的作用或者长久存储.在Tensorflow中当训练模型时,用变量来存储和更新参数.变量包含张量(Tensor)存放于内存 ...
- 从项目上一个子查询扩展学习开来:mysql的查询、子查询及连接查询
上面这样的数据,想要的结果是:如果matchResult为2的话,代表是黑名单.同一个softId,version,pcInfoId的代表是同一个软件,需要去重:同时,如果相同软件里面只要有一个mat ...
- JS 数字左补零函数
/* 左边自动补零 质朴长存法 by lifesinger */ function pad(num, n) { var len = num.toString().length; while(len & ...
- Redis Cluster集群的搭建
redis集群搭建原理: redis是单线程,但是一般的作为缓存使用的话,redis足够了,因为它的读写速度太快了. 官方的一个简单测试: 测试完成了50个并发执行100000个请求. 设置和获取 ...
- 1000个经常使用的Python库和演示样例代码
以下是programcreek.com通过分析大量开源码,提取出的最经常使用的python库. 1. sys (4627) 2. os (4088) 3. re (3563) 4 ...
- 微信小程序自定义分享图片
自定义分享图片 onShareAppMessage: (res) => { if (res.from === 'button') { console.log("来自页面内转发按钮&qu ...
- 运用Unity实现AOP拦截器[结合异常记录实例]
本篇文章将通过Unity实现Aop异常记录功能:有关Unity依赖注入可以看前两篇文章: 1:运用Unity实现依赖注入[结合简单三层实例] 2:运用Unity实现依赖注入[有参构造注入] 另早期 ...