这两道题都是求两个数组之间的重复元素,因此把它们放在一起。

原题地址:

349 Intersection of Two Arrays :https://leetcode.com/problems/intersection-of-two-arrays/description/

350 Intersection of Two Arrays II:https://leetcode.com/problems/intersection-of-two-arrays-ii/description/

题目&&解法:

1.Intersection of Two Arrays:

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

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

Note:

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

这道题目要注意的就是不能重复。我采取的做法是遍历一遍nums1数组,然后和nums2数组比对,假如nums2里面存在并且要返回的数组中没有这个数值,就把他插入要返回的数组里面。很低端的一种做法,代码如下:

class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
vector<int> temp;
for (int i = ; i < nums1.size(); i++) {
if (find(nums2.begin(), nums2.end(), nums1[i]) != nums2.end() && find(temp.begin(), temp.end(), nums1[i]) == temp.end()) {
temp.push_back(nums1[i]);
}
}
return temp;
}
};

2.Intersection of Two Arrays II

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

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

Note:

  • Each element in the result should appear as many times as it shows in both arrays.
  • The result can be in any order.

Follow up:

    • What if the given array is already sorted? How would you optimize your algorithm?
    • What if nums1's size is small compared to nums2's size? Which algorithm is better?
    • What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once?

这道题目比上面的题目复杂了一点,它要求把重复的元素都放进返回的数组里面,我采取了一种非常非常垃圾的做法:先定义一个结构体,一个int类型和一个bool类型,int变量数值复制传入的数组,然后用bool变量标记当前元素的数值是否已经插入要返回的数组。然后采取双层循环逐个比对。代码如下:

class Solution {
public:
vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
struct v{
  int data;
  bool isChoosed;
  };
vector<struct v> struct_num1;
vector<struct v> struct_num2;
for (int i = ; i < nums1.size(); i++) {
struct v t;
t.data = nums1[i];
t.isChoosed = false;
struct_num1.push_back(t);
}
for (int i = ; i < nums2.size(); i++) {
struct v t;
t.data = nums2[i];
t.isChoosed = false;
struct_num2.push_back(t);
}
vector<int> temp;
for (int i = ; i < nums1.size(); i++) {
for (int j = ; j < nums2.size(); j++) {
if (struct_num1[i].data == struct_num2[j].data && struct_num2[j].isChoosed == false && struct_num1[i].isChoosed == false) {
temp.push_back(struct_num2[j].data);
struct_num1[i].isChoosed = true;
struct_num2[j].isChoosed = true;
}
}
}
return temp;
}
};

这种做法让我鄙视我自己,时间复杂度为O(n^2),极高。而且写起来极其麻烦。肯定有简单的方法啊!

根据http://blog.csdn.net/yzhang6_10/article/details/51526070里面的一种比较快的思路:

(1)先对两个数组进行排序

(2)遍历两个数组,比较对应元素:若相等,两个数组的索引同时增加;若不等,较小元素的数组的索引增加。

这是一个极精妙的方法,个人感觉原理和归并数组有点相似。这个算法值得经常去回顾一下,特此记录。

代码如下:

class Solution {
public:
vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
sort(nums1.begin(), nums1.end());
sort(nums2.begin(), nums2.end());
vector<int> result;
for (int i = , j = ; i < nums1.size() && j < nums2.size(); )
{
if (nums1[i] == nums2[j])
{
result.push_back(nums1[i]);
i++;
j++;
}
else if (nums1[i] < nums2[j])
i++;
else if (nums1[i] > nums2[j])
j++;
}
return result;
}
};

[LeetCode] 349 Intersection of Two Arrays && 350 Intersection of Two Arrays II的更多相关文章

  1. [LeetCode] 349. Intersection of Two Arrays 两个数组相交

    Given two arrays, write a function to compute their intersection. Example 1: Input: nums1 = [1,2,2,1 ...

  2. [LeetCode] 350. Intersection of Two Arrays II 两个数组相交II

    Given two arrays, write a function to compute their intersection. Example 1: Input: nums1 = [1,2,2,1 ...

  3. 26. leetcode 350. Intersection of Two Arrays II

    350. Intersection of Two Arrays II Given two arrays, write a function to compute their intersection. ...

  4. LeetCode Javascript实现 169. Majority Element 217. Contains Duplicate(两个对象比较是否相等时,如果都指向同一个对象,a==b才是true)350. Intersection of Two Arrays II

    169. Majority Element /** * @param {number[]} nums * @return {number} */ var majorityElement = funct ...

  5. 【leetcode】350. Intersection of Two Arrays II

    problem 350. Intersection of Two Arrays II 不是特别明白这道题的意思,例子不够说明问题: 是按顺序把相同的元素保存下来,还是排序,但是第二个例子没有重复... ...

  6. LeetCode 349,350 数组的交集

    LeetCode 349: package com.lt.datastructure.Set; import java.util.ArrayList; import java.util.LinkedH ...

  7. LeetCode第[4]题(Java):Median of Two Sorted Arrays 标签:Array

    题目难度:hard There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median ...

  8. LeetCode第[4]题(Java):Median of Two Sorted Arrays (俩已排序数组求中位数)——HARD

    题目难度:hard There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median ...

  9. 【一天一道LeetCode】#350. Intersection of Two Arrays II

    一天一道LeetCode 本系列文章已全部上传至我的github,地址:ZeeCoder's Github 欢迎大家关注我的新浪微博,我的新浪微博 欢迎转载,转载请注明出处 (一)题目 Given t ...

随机推荐

  1. 7.11.3 Java简介

    101Java简介 101Java简介及开发环境搭建 Java简介 编程语言简介 机器语言:纯粹的机器代码 机器语言是有0,1,0,1的二进制代码组成,可以有计算机直接执行.效率最高,但是通用性不强, ...

  2. APUE 3 -- 信号(signal)<I> :概念

    信号可以理解成一种软件中断.他提供了一种异步处理事件的方式.每个信号都有一个与之对应的信号名,这些信号名都带有SIG前缀,如:SIGABRT,SIGALARM.头文件signal.h 中定义了所有的信 ...

  3. Struts2.5 利用Ajax将json数据传值到JSP

    AJAX +JSON=>JSP AJAX AJAX 是一种在无需重新加载整个网页的情况下,能够更新部分网页的技术. 通过在后台与服务器进行少量数据交换,AJAX 可以使网页实现异步更新.这意味着 ...

  4. poj3928 la4329 pingpong

    Description N(3<=N<=20000) ping pong players live along a west-east street(consider the street ...

  5. Python学习笔记之运算符之一

    算数运算符 +加法运算符 -减法运算符 *乘法运算符 /除法运算符 //整除运算符 **乘积运算符(幂运算符) %取模运算符(取余) #!/usr/bin/python # -*- coding: U ...

  6. 传参时Url中有中文报错

    url中如果传了中文,浏览器会报错:The header content contains invalid characters. 原因:浏览器自动把这个url进行decodeURIComponent ...

  7. 在JS事件封装时,addEventListener()方法的this问题

    最近在写js的类库,模仿的是jquery的编程风格,当封装到事件监听的时候发现遇到了一个问题,代码是这样的: 上面是封装的一个事件委托的代码,我以为上面的封装跟普通的事件监听一样简单,结果我在调用时发 ...

  8. 使用jmeter执行多条sql语句

    注意2个地方 1. [JDBC Connection Configuration] 在配置DataBase URL的时候,加上allowMultiQueries=true参数如: jdbc:MySQL ...

  9. Linux平台 Oracle 12cR2 RAC安装Part3:DB安装

    Linux平台 Oracle 12cR2 RAC安装Part3:DB安装 四.DB(Database)安装 4.1 解压DB的安装包 4.2 DB软件安装 4.3 ASMCA创建磁盘组 4.4 DBC ...

  10. MariaDB体验2----CSV文件导入

    之前已经安装好MariaDB,现在需要将一份从Sql Server数据库里面导出的CSV文件导入进MariaDB,期间碰到了各种坑,这里记录一下. HeidiSQL的导入CSV文件的地方在“工具”栏, ...