题目描述
给定长度为n+1的整形数组,数组元素的范围是 1到n 之间,其中有个数重复了很多次,找出这个数
思路分析
思路一:暴力求解
用两层for循环找出数组中的重复数字,时间复杂度为O(N^2)
思路二:哈希表法
用空间换时间的思路。新建一个哈希表,然后遍历数组,如果哈希表中不含有该元素,则将该元素添加到哈希表中;如果哈希表中包含该元素,则返回这个重复元素。时间复杂度为O(logN)
思路三:数组环–时间复杂度为:O(N)
2既是重复数字,也是链表环的开始位置,所以可以用解决链表环的思路来解决数组环
步骤:
1.假定数组长度为length,初始化快指针fast,慢指针slow为length-1
2.从数组末尾开始,执行index = array[index]
,其中fast执行两次。
3.不断的执行第2步,直到fast和slow相遇。
4.借用链表环的起始节点的思路,求出重复元素。
注意:1.题目给定的数组元素介于1到n之间
2.
代码实现
思路一代码实现
public class Solution {
public int findDuplicate(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
} else {
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[i] == nums[j]) {
return nums[i];
}
}
}
}
return 0;
}
}
思路二代码实现
public class Solution {
public int findDuplicate(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
} else {
HashSet<Integer> hashSet = new HashSet<Integer>(); //新建哈希表
for (int i : nums) {
if (!hashSet.contains(i)) { //如果哈希表不包含该元素
hashSet.add(i);
} else {
return i; //返回重复元素
}
}
}
return 0;
}
}
思路三代码实现
public class Solution {
public int findDuplicate(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
} else {
int n = nums.length; //数组长度
//快慢指针(数组下标)指向数组末尾
int fast = n - 1;
int slow = n - 1;
while (true) {
//把当前元素值作为下一个下标!!!
slow = nums[slow] - 1;
fast = nums[fast] - 1;
fast = nums[fast] - 1;
if (fast == slow) {
break;
}
}
//让任意一个指针指向数组的尾部
slow = n - 1;
//向后移动两个指针,直到他们相遇,此时就是数组环的起始节点,也就是数组中的重复元素。
while (slow != fast) {
slow = nums[slow] - 1;
fast = nums[fast] - 1;
}
return slow + 1;
}
}
}