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. jQuery旋转插件—rotate

    jQuery旋转插件,支持Internet Explorer 6.0+ .Firefox 2.0 .Safari 3 .Opera 9 .Google Chrome rotate(angle) 正值表 ...

  2. 十大流行linux

    你可曾知道Linux的魅力或威力来自哪里?那就是,由于众多发行版百花齐放,Linux的阵营日益壮大,每一款发行版都拥有一大批用户,开发者自愿为相关项目投入精力.Linux发行版可谓是形形色色,它们旨在 ...

  3. NGUI自适应屏幕分辨率

    unity官方承诺的新ui系统一直没有推出来,我们的UI使用的是原生的OnGUI系统,刚好UI需要改版,索性就想迁到NGUI上面来,于是看了一下NGUI源码,发现NGUI可以大大的降低DrawCall ...

  4. Weblogic常见故障之二:XAER_NOTA XAException问题的解决

    在weblogic执行XA操作的时候,我们会碰到如下的错误,后来发现是JDBC配置的问题.主要报错:java.sql.SQLException: XA error: XAER_NOTA : The X ...

  5. tracepath 路由跟踪命令

    [root@c1 scripts]# tracepath 100.2.4.144    (备注:linux系统) 1: c1.nulige.com (100.2.4.144) 0.047ms pmtu ...

  6. android sdk下载SDK Platform失败记录

    在使用android sdk manager下载的时候会遇到 下载完毕后,你可能会出现如下图一样的错误,就算重复尝试多次依然无法正常安装 Downloading SDK Platform Androi ...

  7. solr 高亮显示

    官网:https://lucene.apache.org/solr/guide/6_6/highlighting.html#Highlighting-TheUnifiedHighlighter 前言 ...

  8. 【云计算】使用supervisor管理Docker多进程-ntpd+uwsgi+nginx示例最佳实践

    supervisor安装启动: apt-get install supervisor -y # start supervisord nodaemon /usr/bin/supervisord --no ...

  9. 解决:mysql5.7 timestamp默认值0000-00-00 00:00:00 报错

    解决:mysql5.7 timestamp默认值0000-00-00 00:00:00 报错 学习了:https://www.cnblogs.com/cnhkzyy/p/9119339.html se ...

  10. C#秘密武器之表达式树

    一.表达式树入门 Lambda表达式树很复杂,从概念上很难理解清楚,一句话,表达式树是一种数据结构!这里我们通过下面的这个例子来理解一下表达式树,你就能看个大概: lambda表达式树动态创建方法 s ...