剑指offer
1、找出数组中重复的数字。
题目描述:
找出数组中重复的数字。
在一个长度为 n 的数组 nums 里的所有数字都在 0~n-1 的范围内。数组中某些数字是重复的,但不知道有几个数字重复了,也不知道每个数字重复了几次。请找出数组中任意一个重复的数字。
示例 :
输入:
[2, 3, 1, 0, 2, 5, 3]
输出:2 或 3
示例答案:
/**
1、初始化集合为空集合,重复的数字 repeat = -1
2、遍历数组中的每个元素:
将该元素加入HashSet集合中,判断是否添加成功
如果添加失败,说明该元素已经在集合中,因此该元素是重复元素,将该元素的值赋给 repeat,并结束遍历
3、返回 repeat
*/
class Solution {
public int findRepeatNumber(int[] nums) {
Set set = new HashSet();
int repeat = -1;
for (int num : nums) {
if (!set.add(num)) {
repeat = num;
break;
}
}
return repeat;
}
}
改进IDEA运行版本答案:
package com.java.offer_75;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class Solution {
public HashSet findRepeatNumber(int[] nums) {
HashSet set = new HashSet();
HashSet set2 = new HashSet();
for (int num : nums) {
if (!set.add(num)) {
set2.add(num);
}
}
return set2;
}
public static void main(String[] args) {
int [] nums=new int[]{2,5,2,1,5,3,3};
Solution solution=new Solution();
HashSet repeatNumber = solution.findRepeatNumber(nums);
System.out.println("剑指offer第一题:数组中重复的数字n");
System.out.println("重复的数字为:");
Iterator iterator = repeatNumber.iterator();
while (iterator.hasNext()){
Object next = iterator.next();
System.out.println(next);
}
}
}