题目描述:
在一个长度为 n 的数组里的所有数字都在 0 到 n-1 的范围内。数组中某些数字是重复的,但不知道有几个数字是重复的,也不知道每个数字重复几次。请找出数组中任意一个重复的数字。
要求:时间复杂度 O(N),空间复杂度 O(1)
Input:
{2, 3, 1, 0, 2, 5}
Output:
2
解题思路:
题目要求空间复杂度 O(1),因此不能使用排序的方法,不能使用HashSet,也不能使用额外的标记数组。
对于这种数组元素在 [0, n-1] 范围内的问题,可以将值为 i 的元素调整到第 i 个位置上进行求解,即哈希表的方式。具体过程如下图(图片来源于https://github.com/CyC2018/CS-Notes/blob/master/docs/notes/%E5%89%91%E6%8C%87%20offer%20%E9%A2%98%E8%A7%A3.md该作者整理了java开发所需的笔记,强烈推荐,比看书快!):
由于比较简单,直接贴代码
public class Question3 {
private static int deduplicate(int a[]) {
if (a.length < 2 || a == null) {
return -1;
}
// 判断不合格的数
for (int i = 0; i < a.length; i++) {
if (a[i] < 0 || a[i] > a.length - 1) {
return -2;
}
}
// 找重复的数
for (int i = 0; i < a.length; i++) {
while (a[i] != i) {
//如果这个位置上的数等于它hash位置上数,就重复
if (a[i]==a[a[i]]) {
return a[i];
}
swap(a, i, a[i]);
}
}
return -1;
}
public static void swap(int a[], int i, int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
public static void main(String[] args) {
int[] a = { 2, 3, 1, 0, 2, 5, 3 };
System.out.println(deduplicate(a));
}
}