题目描述:
- 找出数组中重复的数字
- 在一个长度为n的数组里的所有数字都在0~n-1的范围内
- 数组中某些数字是重复的,但不知道有几个数字重复了,也不知道,每个数字重复
- 了几次,找出数组中任意一个重复的数字,例如,输入长度为7的数组{2,3,1,0,2,5,3}
- 那么对应的输出是重复的数字2 或者3
三个思路:
方法1 :把输入的数组排序,然后从排序后的数组中找到重复的数字,只需要遍历查找即可,
// 排序一个长度为n 的数组的时间复杂度是O(nlogn)
代码实现:
public static Set<Integer> repeat(int[] a) {
// 这里返回Set是因为,Set 是无序的。
Set<Integer> set = new HashSet<Integer>();
Arrays.sort(a);// 对数组排序
for (int i = 0; i < a.length - 1; i++) {
if (a[i] == a[i + 1])
set.add(a[i]);
}
return set;
}
方法2: 方法2: 可以用哈希标来解决这个问题,从头到尾按顺序扫描数组的每一个数字,每扫描到一个数字的时候,
// 都去判断一下是否包含了这个数字,如果哈希表没有这个数字,就加入哈希标,如果哈希标
// 存在这个数字,就找到一个重复的数字
public static Set<Integer> repeat1(int[] a) {
// 这里返回Set是因为,Set 是无序的。
Set<Integer> set = new HashSet<Integer>();
Set<Integer> set1 = new HashSet<Integer>();
for (int i = 0; i < a.length; i++) {
if (!set.contains(a[i])) {
set.add(a[i]);
} else {
set1.add(a[i]);
}
}
return set1;
}
方法3: 用换位的方式去寻找这个集合数组
// 我们重排这个数组,从头到尾以此扫描这个数组中的每个数字,
// 当扫到下标是i 的数字的时候,首先比较这个数字m 是不是等于i
// 如果是,则接着扫面下一个数字,如果不是,则再拿他和第m个数字进行比较,如果和第m个数字相等
// 就找到了一个重复的数字
public static Set<Integer> repeat2(int[] a) {
// 这里返回Set是因为,Set 是无序的。
Set<Integer> set1 = new HashSet<Integer>();
for (int i = 0; i < a.length; i++) {
if (a[i] != i) {
if (a[i] == a[a[i]])
set1.add(a[i]);
else {
int temp = a[i];
a[i] = a[temp];
a[temp] = temp;
}
}
}
return set1;
}
测试代码:
public static void main(String[] args) {
int[] a = { 1, 2, 2, 2, 4, 5, 5, 7, 8 };
Set<Integer> b = repeat(a); for (int c : b) { System.out.println(c); }
Set<Integer> repeat1 = repeat1(a); for (int i : repeat1) {
System.out.println(i); }
Set<Integer> repeat2 = repeat2(a);
for (int i : repeat2) {
System.out.println(i);
}
}