2018-06-18 lintCode633 Find the duplicate number

Description

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.

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(n^2).
There is only one duplicate number in the array, but it could be repeated more than once.

中文描述:
给出一个数组 nums 包含 n + 1 个整数,每个整数是从 1 到 n (包括边界),保证至少存在一个重复的整数。假设只有一个重复的整数,找出这个重复的数。

Example
Given nums = [5,5,4,3,2,1] return 5
Given nums = [5,4,4,3,2,1] return 4

题目分析
这道题知道和二分法有关, 但是一开始并不知道如何去确定判断答案是否猜对的判断条件,看了答案以后发现和lintCode183 wood cut的判断条件是类似的。 这个数组是从1到n的, 一共n + 1个元素。 假设这个数组是 [7, 6, 5, 4, 4, 3, 2, 1] 那么假设随机选一个数 3, 小于等于3 的元素个数只有3个, 那就是1, 2, 3。 如果选2, 小于等于2的就只有两个元素。 那如果选5, 小于等于5的元素是6, 选6和选7也是一样, 小于或等于他们自身的元素个数都要多1个。 因此以这个条件就可以作为判断二分猜答案是否正确的标准了。

代码如下:

public class Solution {
        /**
         * @param nums: an array containing n + 1 integers which is between 1 and n
         * @return: the duplicate one
         */
        public int findDuplicate(int[] nums) {
            // write your code here
            int l = 1, r = nums.length - 1;

            while(l + 1 < r)
            {
                int mid = l + (r - l) / 2;
                if(count(nums, mid) <= mid)
                    l = mid;
                else
                    r = mid;

            }

            if(count(nums, l) <= l)
                return r;
            return l;

        }

        public int count(int[] nums, int mid)
        {
            int count = 0;
            for(int num: nums)
            {
                if(num <= mid)
                    count++;
            }
            return count;
        }
    }

结合之前的分析, 如果count函数返回的结果小于或者等于mid, 说明重复的那个数不在这个范围内, 那么移动左指针, 反之, 移动右指针。 最后同样要再判断一下到底是l 还是r。

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 13,002评论 0 33
  • 在C语言中,五种基本数据类型存储空间长度的排列顺序是: A)char B)char=int<=float C)ch...
    夏天再来阅读 4,146评论 0 2
  • 嗨,我是子铭。 全文:1742。 适合阅读群体:子铭自身/子铭朋友 适合阅读速度:慢读,分析我。 懒散袭击了我,直...
    陈子铭阅读 1,133评论 0 0
  • 无论是什么样的人,都应该好好学习,提升自己的各方面能力,只有这样,才能拥抱美好的未来。就像辛夷坞《应许之日》所说:...
    爱图腾阅读 213评论 0 2

友情链接更多精彩内容