题目描述
在一个长度为 n 的数组里的所有数字都在 0 到 n-1 的范围内。数组中某些数字是重复的,但不知道有几个数字是重
复的,也不知道每个数字重复几次。请找出数组中任意一个重复的数字。
解题思路
对于这种数组元素在 [0, n-1] 范围内的问题,可以将值为 i 的元素调整到第 i 个位置上进行求解。
要求时间复杂度 O(N),空间复杂度 O(1)。因此不能使用排序的方法,也不能使用额外的标记数组。
import java.util.Scanner;
public class Three {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
int[] numbers = stringToArray(str);
sc.close();
int[] duplication = new int[1];
int length = numbers.length;
boolean flag = duplicate(numbers,length,duplication );
System.out.println(flag);
System.out.println(duplication[0]);
}
public static boolean duplicate(int numbers[], int length, int[] duplication) {
if (numbers == null || length <= 0)
return false;
for (int i = 0; i < length; i++) {
while (numbers[i] != i) {
if (numbers[i] == numbers[numbers[i]]) {
duplication[0] = numbers[i];
return true;
}
swap(numbers, i, numbers[i]);
}
}
return false;
}
private static void swap(int[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
private static int[] stringToArray(String str) {
String[] temp = str.split(" ");
int[] result = new int[temp.length];
for (int i = 0; i < temp.length; i++) {
result[i] = Integer.valueOf(temp[i]);
}
return result;
}
}
Input:
{2, 3, 1, 0, 2, 5}
Output:
true
2
参考资料
https://github.com/CyC2018/CS-Notes/blob/master/notes/%E5%89%91%E6%8C%87%20Offer%20%E9%A2%98%E8%A7%A3%20-%20%E7%9B%AE%E5%BD%95.md