给的数组中找出重复的数字?
方法一:set.add(num) 返回值是boolean类型,来实现巧妙去重
class Solution {
public int findRepeatNumber(int[] nums) {
Set<Integer> set = new HashSet<>();
for (int num : nums) {
if (!set.add(num))
return num;
}
return -1;
}
}
方法二:
public int findRepeatNumber(int[] nums) {
Arrays.sort(nums);
for (int i = 1; i < nums.length; i++) {
if (nums[i] == nums[i - 1])
return nums[i];
}
return -1;
}
方法三:
class Solution {
public int findRepeatNumber(int[] nums) {
Set<Integer> set = new HashSet<>();
for(int num:nums){
if(!set.contains(num)){
set.add(num);
}else{
return num;
}
}
return -1;
}
}