资讯专栏INFORMATION COLUMN

[LeetCode] Find the Duplicate Number

MoAir / 2446人阅读

Problem

Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one.

Note:

You must not modify the array (assume the array is read only).
You must use only constant, O(1) extra space.
Your runtime complexity should be less than O(n2).
There is only one duplicate number in the array, but it could be repeated more than once.

Solution
class Solution {
    public int findDuplicate(int[] nums) {
        int start = 0, end = nums.length-1;
        while (start <= end) {
            int mid = start + (end-start)/2;
            if (count(nums, mid) <= mid) {
                start = mid+1; //numbers no larger than mid <= mid, so mid is safe, search second half
            } else end = mid-1; //numbers less than mid > mid, so there is duplicate in first half
        }
        return start; //when start > end, 
    }
    private int count(int[] nums, int k) {
        int count = 0;
        for (int num: nums) {
            if (num <= k) count++;
        }
        return count;
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/69307.html

相关文章

  • LeetCode[287] Find the Duplicate Number

    摘要:复杂度思路每次通过二分法找到一个值之后,搜索整个数组,观察小于等于这个数的个数。考虑,小于这个位置的数的个数应该是小于等于这个位置的。要做的就是像找中的环一样,考虑重复的点在哪里。考虑用快慢指针。代码把一个指针放回到开头的地方 LeetCode[287] Find the Duplicate Number Given an array nums containing n + 1 in...

    canopus4u 评论0 收藏0
  • [LeetCode] 287. Find the Duplicate Number

    Problem Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate nu...

    rickchen 评论0 收藏0
  • [Leetcode] Find the Duplicate Number 找到重复数字

    摘要:暴力法复杂度时间空间思路如果不用空间的话,最直接的方法就是选择一个数,然后再遍历整个数组看是否有跟这个数相同的数就行了。二分法复杂度时间空间思路实际上,我们可以根据抽屉原理简化刚才的暴力法。 Find the Duplicate Number Given an array nums containing n + 1 integers where each integer is bet...

    chnmagnus 评论0 收藏0
  • [LeetCode] 609. Find Duplicate File in System

    Problem Given a list of directory info including directory path, and all the files with contents in this directory, you need to find out all the groups of duplicate files in the file system in terms o...

    sf190404 评论0 收藏0
  • leetcode 部分解答索引(持续更新~)

    摘要:前言从开始写相关的博客到现在也蛮多篇了。而且当时也没有按顺序写现在翻起来觉得蛮乱的。可能大家看着也非常不方便。所以在这里做个索引嘻嘻。顺序整理更新更新更新更新更新更新更新更新更新更新更新更新更新更新更新更新 前言 从开始写leetcode相关的博客到现在也蛮多篇了。而且当时也没有按顺序写~现在翻起来觉得蛮乱的。可能大家看着也非常不方便。所以在这里做个索引嘻嘻。 顺序整理 1~50 1...

    leo108 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<