Find the Duplicate Number

来源:互联网 发布:mysql innerjoin 编辑:程序博客网 时间:2024/06/07 06:05

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:

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

这道题考查的是二分搜索。还是参考了网上的思路。感觉还是比较有难度的题。

代码:

public int findDuplicate(int[] nums) {        if(nums == null || nums.length == 0) return 0;                int low = 1;        int high = nums.length-1;// 0~n n个数字,nums.length = n + 1                while(low<high){            int mid = low + (high - low)/2;            int count = 0;            for(int a : nums){                if(a<=mid){                    count++;                }            }            if(count <=mid){                low = mid +1;            }else{                high = mid;            }        }        return low;    }


0 0
原创粉丝点击