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. Android内存优化2 了解java内存分配 2

    JVM内存模型 Java虚拟机(Java Virtual Machine=JVM)的内存空间分为五个部分,分别是: 1. 程序计数器 2. Java虚拟机栈 3. 本地方法栈 4. 堆 5. 方法区. ...

  2. python读取大文件的方法及mmap内存映射模块

    python计算文件的行数和读取某一行内容的实现方法 :最简单的办法是把文件读入一个大的列表中,然后统计列表的长度.如果文件的路径是以参数的形式filepath传递的,那么只用一行代码就可以完成我们的 ...

  3. NormalMap 贴图 【转】

    转载: http://www.zwqxin.com/archives/shaderglsl/review-normal-map-bump-map.html   说起Normal Map(法线贴图),就 ...

  4. DevExpress 小计 GridControl 隔行换行

    摘自: http://www.cnblogs.com/yuerdongni/archive/2012/09/08/2676753.html 1. 如何解决单击记录整行选中的问题 View->Op ...

  5. EasyUI-子页面增加显示tabs的一个问题

    在父页面点个链接能动态看到子页面的情况太简单,请看easyUI官网:http://www.jeasyui.com/tutorial/layout/tabs2.php现在说的是在子页面点个按钮也能触发增 ...

  6. C#/Sqlite-单机Window 程序 sqlite 数据库实现

    数据库分析和选择 Excel 文件 做数据源 限制性比较强,且不适合查询,分析 等操作 Access 数据库 Access 管理数据界面和功能不强 mysql 和sql server 功能满足,但需要 ...

  7. Windows录音API学习笔记

    Windows录音API学习笔记 结构体和函数信息  结构体 WAVEINCAPS 该结构描述了一个波形音频输入设备的能力. typedef struct { WORD      wMid; 用于波形 ...

  8. XP系统如何把桌面图标变大

    右击桌面,属性,外观,高级,在项目里面找到图标,大小改为你喜欢的样式.   我测试的结果是:图标大小改为42,字体大小改为8,图标垂直间距改为100,水平间距改为54效果不错.

  9. v - on

    1. v-on绑定:on:click点击事件,再触发方法里面的add()或del() 2. 详情查看官方文档:https://cn.vuejs.org/v2/api/#v-on <!DOCTYP ...

  10. (原创)开发使用Android studio所遇到的一些问题总结

    1.Android studio下载链接地址(无需FQ):包括先行版和正式版(推荐使用正式版bug少) http://www.androiddevtools.cn/ 2.第一次安装避免成功先不要急着打 ...