leet287:寻找重复数

本文深入探讨了二分查找法和快慢指针法在解决数组中重复元素问题的应用。通过具体代码示例,展示了不同算法的实现方式,包括二分查找、快慢指针、HashSet、排序比较、双重循环和HashMap计数等方法,对比了各自的运行效率。

在这里插入图片描述
二分查找法

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;
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值