Find The Duplicate Number

来源:互联网 发布:连通区域图像分割算法 编辑:程序博客网 时间:2024/06/05 02:44

题目描述

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.

题目解答

题目分析

二分查找
1…10, 小于等于5的一定有5个,如果多于5个,就在lower part, 等于5个就是upper part.

代码实现

public class Solution {    public int findDuplicate(int[] nums) {        if(nums == null || nums.length == 0)            return 0;        int len = nums.length;        int low = 1, high = len - 1;        while(low < high) {            int middle = (low + high) / 2;            int count = counts(nums, middle, len);            if(count > middle)                high = middle;            else                 low = middle + 1;        }        return low;    }    public int counts(int[] nums, int middle, int len) {        int ret = 0;        for(int i = 0; i < len; i++) {            if(nums[i] <= middle)                ret++;        }        return ret;    }}
0 0
原创粉丝点击