LeetCode题解 -- 双指针(287)

Find the Duplicate Number

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.

相似题目 《剑指Offer》题解 – 面试题03. 数组中重复的数字

时间复杂度:O(n^2)
空间复杂度:O(1)

可能会在某些用例上出现错误,可以在count 等于 mid 时,再进入小区间判断是否有重复数字

class Solution {
    public int findDuplicate(int[] nums) {
        int length = nums.length;
        int lo = 1;
        int hi = length;
        while(lo < hi){
            int mid = (hi - lo)/2 + lo;
            int count = getCount(nums,mid);
            if(count > mid){
                hi = mid ;
            }else{
                lo = mid + 1;
            }
        }

        return lo;
    }
    
    public int getCount(int[] nums,int target){
        int length = nums.length;
        int count = 0;
        for(int i = 0;i < length;i++){
            if(nums[i] <= target){
                count++;
            }
        }
        
        return count;
    }
}
发布了30 篇原创文章 · 获赞 0 · 访问量 871

猜你喜欢

转载自blog.csdn.net/fantow/article/details/104700523