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 ...
随机推荐
- web及网络基础
关于本http系列博客 本系列博客内容全部来自或参考自<图解http>,不过博客中的图示基本上为博主自己手动绘制,部分图可能来自其它地方,但都有标注. 常见协议的分类 分层 常见协议 应用 ...
- 【mybatis】mybatis多表联查,存在一对多关系的,实体中使用List作为字段接收查询结果的写法
实体如下: IntegralGoods 积分商品 IntegralGoodsImg 积分商品图片 ShelfLog 积分商品自动上架记录 IntegralGoods :IntegralGoodsIm ...
- 【FTP】使用org.apache.commons.net.ftp.FTPClient 实现FTP的上传下载
在此之前,在项目中加上FTP的架包 第一步:配置FTP服务器的相关配置 FtpConfig.java 实体类(配置类) package com.sxd.ftp; public class FtpCo ...
- Log4j 日志级别
转自:http://michales003.iteye.com/blog/1160605 日志记录器(Logger)是日志处理的核心组件.log4j具有5种正常级别(Level).: 1.static ...
- 动态jdk启动项目
昨天遇到,服务器安装jdk1.7,但是springboot项目用jdk1.8编译的,所以需要指定jdk版本启动: nohup /root/jdk1.8.0_11/bin/java -jar /root ...
- python修改和获取进程名字:setproctitle
参考: https://pypi.org/project/setproctitle/
- iOS: 使用故事板和xib设置按钮圆角方法
使用storyboard如何设置圆角或边框? 通过storyboard的 运行时属性runtime attribute,可以对Button设置圆角或者边框 1.很多人都知道,通常设置一个 Button ...
- [Todo] Git & 版本控制学习
下面这篇写的非常好.git分支介绍,有图.好好看这一篇,就懂了: http://www.open-open.com/lib/view/open1328069889514.html 该系列还有不少文章, ...
- 同步和异步 阻塞和非阻塞 IO多路复用和select总结
同步和异步的概念 同步是指用户线程发起IO请求后,需要等待或者轮询内核IO操作完成后才能继续执行: 异步是指用户线程发起IO请求后仍继续执行,当内核IO操作完成后会通知用户线程或者调用用户线程注册的回 ...
- 使用虚拟机运行Ubuntu时,主机与宿主机共享文件的方法。
简介: 首先设置虚拟机: 虚拟机 -> 设置-> Hardware -> Network Adapter,在网络连接处设置为 “桥接:直接连接到物理网络”,“NAT:使用已共享的主机 ...