鱼C论坛

 找回密码
 立即注册
查看: 1746|回复: 0

[学习笔记] leetcode 287. Find the Duplicate Number

[复制链接]
发表于 2019-9-29 01:57:31 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
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.

Example 1:

Input: [1,3,4,2,2]
Output: 2
Example 2:

Input: [3,1,3,4,2]
Output: 3
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.暴力解法
class Solution {
    public int findDuplicate(int[] nums) {
        if(nums.length == 0) return 0;
        
        
        for(int i = 0; i< nums.length-1; i++) {
            for(int j = i+1; j < nums.length; j++){
                if(nums[i] == nums[j]) {
                    // System.out.println(nums[i]);
                    return nums[i];
                }
                
            }
        }
        
        return -1;
    }
}

2.two pointers
class Solution {
    public int findDuplicate(int[] nums) {
        int slow = nums[0];
        int fast = nums[0];
        
        slow = nums[slow];
        fast = nums[nums[fast]];
        
        while(slow != fast){
            slow = nums[slow];
            fast = nums[nums[fast]];
        }
        
        int a = nums[0];
        int b = slow;
        
        while(a != b){
            
            a = nums[a];
            b = nums[b];
        }
        return a;
    }
}

3.二分法
class Solution {
    public int findDuplicate(int[] nums) {
        int min = 0;
        int max = nums.length;
        
        while(min <= max){
            int mid = (max - min)/2 + min;
            int count = 0;
            for(int i = 0; i < nums.length; i++){
                
                if(nums[i] <= mid){
                    count++;
                }
            }
            
            if(count > mid){
                max = mid -1;
            }
            else{
                min = mid + 1;
            }
        }
        
        return min;
    }
}

本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-6-24 03:07

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表