LeetCode 287. 寻找重复数

题目:

给定一个包含 n + 1 个整数的数组 nums,其数字都在 1 到 n 之间(包括 1 和 n),可知至少存在一个重复的整数。假设只有一个重复的整数,找出这个重复的数。

示例 1:
输入: [1,3,4,2,2]
输出: 2

示例 2:
输入: [3,1,3,4,2]
输出: 3

说明:

  • 不能更改原数组(假设数组是只读的)。
  • 只能使用额外的 O(1) 的空间。
  • 时间复杂度小于 O(n2) 。
  • 数组中只有一个重复的数字,但它可能不止重复出现一次。

题解:

/**
 * @Author dfpeng
 * @Date 2019/7/25
 */
public class Solution {
    /**
     * 在网上看到一种很巧妙的解法,
     * 现在还没想太明白,留着日后再看
     * @param nums
     * @return
     */
    public static int findDuplicate(int[] nums) {
        int res = 0;
        for (int fast = 0; res != fast || fast == 0; ) {
            res = nums[res];
            fast = nums[nums[fast]];
        }
        for (int i = 0; res != i; i = nums[i]) {
            res = nums[res];
        }
        return res;
    }


    /**
     * 先计算mid,然后统计数组中<=mid的元素个数count
     * 如果count<=mid,则说明重复的数字在[mid+1,high]范围中
     * 否则的话在[low,mid]范围中
     * 一直重复这种操作,直到low==high
     * @param nums
     * @return
     */
    public static int solve(int[] nums){
        int len=nums.length;
        int low=0,high=len-1;
        int count;
        while (low<high){
            int mid=(low+high)>>1;
            count=0;
            for (int i = 0; i <len ; i++) {
                if (nums[i]<=mid){
                    count++;
                }
            }
            if (count<=mid){
                low=mid+1;
            }else{
                high=mid;
            }
        }
        return low;
    }



    public static void main(String[] args) {
        int res=findDuplicate(new int[]{2,5, 9 ,6,9,3,8, 9 ,7,1});
        System.out.println(res);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值