題目:
面試題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;
}
}