题目:
面试题03. 数组中重复的数字
本题考查的知识点是:数组、哈希表
思路:
- 思路一:使用数据结构哈希表 Set 来实现。题目要求只找到任意一个重复的数字即可。在向set中添加元素时,set会对已有的元素进行对比,若已经存在相同元素,那么久返回false。
- 思路二:自定义一个哈希表结构进行存储,在插入哈希表时对已有元素进行判断
优势:
相对线性表的查找要更加的迅速,哈希查找,不需要经过遍历比较过程。
实现:
class Solution {
/**
* 方法一:
* 使用数据结构 散列表
*/
// public int findRepeatNumber(int[] nums) {
// Set set = new HashSet<Integer>();
// int repeat = -1;
// for (Integer item : nums) {
// if (!set.add(item)){
// repeat = item;
// break;
// }
// }
// return repeat;
// }
/**
* 方法二:
* 使用数组模拟散列表
*/
public int findRepeatNumber(int[] nums){
int[] arr = new int[nums.length];
for (int i = 0; i < nums.length; i++) {
if (arr[nums[i]] == 1)
return nums[i];
arr[nums[i]]++;
}
return -1;
}
}