leetcode里的剑指offer 03 :https://leetcode-cn.com/problems/shu-zu-zhong-zhong-fu-de-shu-zi-lcof/
找出数组中重复的数字。
在一个长度为 n 的数组 nums 里的所有数字都在 0~n-1 的范围内。数组中某些数字是重复的,但不知道有几个数字重复了,也不知道每个数字重复了几次。请找出数组中任意一个重复的数字。
一开始想到的是运用遍历数组的方法
class Solution {
public int findRepeatNumber(int[] nums) {
for(int i=0; i< nums.length; i++){
for(int j =(i++);j< nums.length; j++){
if(nums[i]==nums[j])
return nums[i];
}
}
return -1;
}
}
通过2个for循环,从数组的第一个数开始,依次对后面的数组进行比较。出现重复的数之后,就返回重复的值。
但这个方法相对消耗运算时间,所以用哈希算法更好。
哈希表算法
关于hash,HashSet是set接口的实现类,储存的是无序,且唯一的对象,所以不能用索引的方法。
HashSet的各种方法:
增加 add(null); 删除 remove(news); 对比查找 contains(news); 清空集合 clear(); 获取长度 size();
class Solution {
public int findRepeatNumber(int[] nums) {
Set<Integer> set = new HashSet<>();
for(int i : nums) {
if(set.contains(i))
return i;
set.add(i);
}
return -1;
}
}
先创建一个HashSet用来存放数字,然后遍历数组nums;用 对比查找的方法,如果有重复离开返回这个数字;
如果和前面的数字没有重复,则将这个数字添加到HashSet当中。