作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/


[LeetCode]

题目地址:https://leetcode.com/problems/intersection-of-two-arrays/

  • Difficulty: Easy

题目描述

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

Example 1:

Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2]

Example 2:

Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [9,4]

Note:

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

题目大意

找出两个数组中共同出现的数字,保证结果中返回的数字是唯一的,返回结果的顺序无所谓。

解题方法

方法一:Java解法,HashSet

每次都要看解析啊摔!用HashSet去除每个数组的重复元素,统计重复出现的元素即可。java只有元素的个数确定了才能新建数组,所以这里注意一下。

public class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
HashSet<Integer> set1=new HashSet<Integer>();
for(int i : nums1){
set1.add(i);
}
HashSet<Integer> set2=new HashSet<Integer>();
for(int i: nums2){
if(set1.contains(i)){
set2.add(i);
}
}
int answer[]=new int[set2.size()];
int i=0;
for(int n:set2){
answer[i++]=n;
}
return answer;
}
}

AC:8 ms

方法二:Python解法,set

还是python对于这种多种数据结构的题处理来方便。打败96%的提交。

class Solution(object):
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
return list(set(nums1) & set(nums2))

日期

2017 年 1 月 8 日
2018 年 11 月 11 日 —— 剁手节快乐

最新文章

  1. javascript的垃圾收集机制
  2. Eclipse+MinGW+Boost环境搭建
  3. 用git写书
  4. c#如何区分静态只读变量和常量
  5. Zabbix discoverer processes more than 75% busy
  6. php修改和增加xml结点属性
  7. 感知器算法PLA
  8. 为什么Java byte 类型的取值范围是-128~127 (转)
  9. CodeForces 546C(队列)
  10. 重置MySQL的root用户密码(Window)
  11. 转:C# 中的委托和事件
  12. linux下挂载iso镜像文件(转)
  13. POJ 1236 Network of Schools(tarjan算法 + LCA)
  14. python编程快速上手之第10章实践项目参考答案
  15. Qt编写导航按钮
  16. Java中死锁的定位与修复
  17. SpringMvc 请求中日期类型参数接收一二事儿
  18. 手动脱壳—dump与重建输入表(转)
  19. spring cloud + mybatis 分布式 微服务 b2b2c 多商户商城 全球部署方案
  20. 1257: [CQOI2007]余数之和

热门文章

  1. R语言与医学统计图形-【19】ggplot2坐标轴调节
  2. 1.TwoSum-Leetcode
  3. orcale =&gt; 含义
  4. hbase参数调优
  5. 日常Java 2021/10/1
  6. Vue 前端配置多级目录实践(基于Nginx配置方式)
  7. Netty之Channel*
  8. nodejs-Path模块
  9. 【编程思想】【设计模式】【行为模式Behavioral】访问者模式Visitor
  10. Tomcat(2):配置Tomcat