LeetCode编程练习 - 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.
给定两个数组,编写一个函数来计算它们的交集。结果中的每个元素必须是唯一的,结果可以是任何顺序。
思路:
考虑到无序数组,遍历两个数组,然后定义两个哈希集合,一个用来装载num1数组,一个用来装载两个数组相同的数值,判断集合中是否存在这个值,若存在添加,若不存在,不做任何处理。
运行结果会显示错误,“无法将‘int[]’转换为int”,更改对n的定义,仍然存在错误,查看解决方案,发现解决方案中有一步是将哈希表转换成int型数组,表示集合长度只能用到Count,而Length是看做一个整体,一般面向对象String。