287. Find the Duplicate Number

来源:互联网 发布:网易对战平台mac版 编辑:程序博客网 时间:2024/05/16 17:31

题目

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 class Solution {    // 暴力搜索法    public int findDuplicate(int[] nums) {        int res = 0;        for(int num : nums){            int time = 0;            for(int n : nums){                if(num == n)                    time++;            }            if(time >= 2){                res = num;                break;            }        }        return res;    }}
分析:统计每一个数字出现的次数,找到重复的数字。时间复杂度O(n^2)

二分法:

public class Solution {    public int findDuplicate(int[] nums) {        int min = 0, max = nums.length - 1;        while(min <= max){            // 找到中间那个数            int mid = min + (max - min) / 2;            int cnt = 0;            // 计算总数组中有多少个数小于等于中间数            for(int i = 0; i < nums.length; i++){                if(nums[i] <= mid){                    cnt++;                }            }            // 如果小于等于中间数的数量大于中间数,说明前半部分必有重复            if(cnt > mid){                max = mid - 1;            // 否则后半部分必有重复            } else {                min = mid + 1;            }        }        return min;    }}

映射找环法(不理解)

传送门
0 0
原创粉丝点击