
二分查找法
public static int findDuplicate(int[] nums) {//4ms
int len = nums.length;
int left = 0;
int right = len;
while (left < right) {
// int mid = left + (right - left + 1) / 2;
int mid = (left + right + 1) >>> 1;
int counter = 0;
for (int num : nums) {
if (num < mid) {
counter += 1;
}
}
if (counter >= mid) {
right = mid - 1;
} else {
left = mid;
}
}
return left;
}
快慢指针,面试不推荐
public static int findDuplicate5(int[] nums) {//0ms
int tortoise = nums[0];
int hare = nums[0];
do {
tortoise = nums[tortoise];
hare = nums[nums[hare]];
} while (tortoise != hare);
// Find the "entrance" to the cycle.
int ptr1 = nums[0];
int ptr2 = tortoise;
while (ptr1 != ptr2) {
ptr1 = nums[ptr1];
ptr2 = nums[ptr2];
}
return ptr1;
}
public static int findDuplicate4(int[] nums) {//5ms
HashSet<Integer> set = new HashSet<>();
for (int num:nums){
if(set.contains(num))
return num;
else
set.add(num);
}
return 1;
}
public static int findDuplicate3(int[] nums) {//4ms
Arrays.sort(nums);
for (int i = 1; i < nums.length; i++) {
if(nums[i] ==nums[i-1])
return nums[i];
}
return 1;
}
自己做的
public static int findDuplicate2(int[] nums) {//166ms
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 1;
}
public static int findDuplicate1(int[] nums) {//12ms
HashMap<Integer,Integer> map = new HashMap<>();
for (int num:nums){
map.put(num,map.getOrDefault(num,0)+1);
if (map.get(num)>1)
return num;
}
return 1;
}
本文深入探讨了二分查找法和快慢指针法在解决数组中重复元素问题的应用。通过具体代码示例,展示了不同算法的实现方式,包括二分查找、快慢指针、HashSet、排序比较、双重循环和HashMap计数等方法,对比了各自的运行效率。
1万+

被折叠的 条评论
为什么被折叠?



