题目

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.

分析

查找重复数字,给定一个含有n+1个元素的数组,每个元素的范围是[0,n],数组中只含有一个重复元素,但其可以出现多次,找出该元素。

要求:

  1. 不能修改原数组;
  2. 空间复杂度为常量O(1);
  3. 时间复杂度小于O(n^2);

多种方法对比参考博客

哈希表法

复杂度

时间 O(N) 空间 O(N)

思路

遍历数组时,用一个集合记录已经遍历过的数,如果集合中已经有了说明是重复。但这样要空间,不符合。

暴力法

复杂度

时间 O(N^2) 空间 O(1)

思路

如果不用空间的话,最直接的方法就是选择一个数,然后再遍历整个数组看是否有跟这个数相同的数就行了。

排序法

复杂度

时间 O(NlogN) 空间 O(1)

思路

更有效的方法是对数组排序,这样遍历时遇到前后相同的数便是重复,但这样要修改原数组,不符合要求。

二分法

复杂度

时间 O(NlogN) 空间 O(1)

思路

实际上,我们可以根据抽屉原理简化刚才的暴力法。我们不一定要依次选择数,然后看是否有这个数的重复数,我们可以用二分法先选取n/2,按照抽屉原理,整个数组中如果小于等于n/2的数的数量大于n/2,说明1到n/2这个区间是肯定有重复数字的。比如6个抽屉,如果有7个袜子要放到抽屉里,那肯定有一个抽屉至少两个袜子。这里抽屉就是1到n/2的每一个数,而袜子就是整个数组中小于等于n/2的那些数。这样我们就能知道下次选择的数的范围,如果1到n/2区间内肯定有重复数字,则下次在1到n/2范围内找,否则在n/2到n范围内找。下次找的时候,还是找一半。

注意

我们比较的mid而不是nums[mid]

因为mid是下标,所以判断式应为cnt > mid,最后返回min

代码

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;
}
}

映射找环法

复杂度

时间 O(N) 空间 O(1)

思路

假设数组中没有重复,那我们可以做到这么一点,就是将数组的下标和1到n每一个数一对一的映射起来。比如数组是213,则映射关系为0->2, 1->1, 2->3。假设这个一对一映射关系是一个函数f(n),其中n是下标,f(n)是映射到的数。如果我们从下标为0出发,根据这个函数计算出一个值,以这个值为新的下标,再用这个函数计算,以此类推,直到下标超界。实际上可以产生一个类似链表一样的序列。比如在这个例子中有两个下标的序列,0->2->3。

但如果有重复的话,这中间就会产生多对一的映射,比如数组2131,则映射关系为0->2, {1,3}->1, 2->3。这样,我们推演的序列就一定会有环路了,这里下标的序列是0->2->3->1->1->1->1->…,而环的起点就是重复的数。

所以该题实际上就是找环路起点的题,和Linked List Cycle II一样。我们先用快慢两个下标都从0开始,快下标每轮映射两次,慢下标每轮映射一次,直到两个下标再次相同。这时候保持慢下标位置不变,再用一个新的下标从0开始,这两个下标都继续每轮映射一次,当这两个下标相遇时,就是环的起点,也就是重复的数。对这个找环起点算法不懂的,请参考Floyd’s Algorithm。

注意

第一次找快慢指针相遇用do-while循环

代码

public class Solution {
public int findDuplicate(int[] nums) {
int slow = 0;
int fast = 0;
// 找到快慢指针相遇的地方
do{
slow = nums[slow];
fast = nums[nums[fast]];
} while(slow != fast);
int find = 0;
// 用一个新指针从头开始,直到和慢指针相遇
while(find != slow){
slow = nums[slow];
find = nums[find];
}
return find;
}
}

AC代码

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

GitHub测试程序源码

LeetCode(287)Find the Duplicate Number的更多相关文章

  1. 数组和矩阵(1)——Find the Duplicate Number

    Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), pro ...

  2. LeetCode(171) Excel Sheet Column Number

    题目 Related to question Excel Sheet Column Title Given a column title as appear in an Excel sheet, re ...

  3. LeetCode(220) Contains Duplicate III

    题目 Given an array of integers, find out whether there are two distinct indices i and j in the array ...

  4. Leetcode(4)寻找两个有序数组的中位数

    Leetcode(4)寻找两个有序数组的中位数 [题目表述]: 给定两个大小为 m 和 n 的有序数组 nums1 和* nums2. 请你找出这两个有序数组的中位数,并且要求算法的时间复杂度为 O( ...

  5. LeetCode(275)H-Index II

    题目 Follow up for H-Index: What if the citations array is sorted in ascending order? Could you optimi ...

  6. LeetCode(154) Find Minimum in Rotated Sorted Array II

    题目 Follow up for "Find Minimum in Rotated Sorted Array": What if duplicates are allowed? W ...

  7. LeetCode(122) Best Time to Buy and Sell Stock II

    题目 Say you have an array for which the ith element is the price of a given stock on day i. Design an ...

  8. LeetCode(116) Populating Next Right Pointers in Each Node

    题目 Given a binary tree struct TreeLinkNode { TreeLinkNode *left; TreeLinkNode *right; TreeLinkNode * ...

  9. LeetCode(113) Path Sum II

    题目 Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given ...

随机推荐

  1. net Core 2.0应用程序发布到IIS

    .net Core 2.0应用程序发布到IIS上注意事项   .net Core2.0应用程序发布window服务器报错容易错过的配置. 1.应用程序发布. 2.IIS上新建网站. 3.应用程序池选择 ...

  2. 超全面的vue.js使用总结

    一.Vue.js组件 vue.js构建组件使用 Vue.component('componentName',{ /*component*/ }): 这里注意一点,组件要先注册再使用,也就是说: Vue ...

  3. 4. 把一幅彩色图像的R、G、B分量单独显示。

    #include <cv.h> #include <highgui.h> int main(void) { IplImage* oo = cvLoadImage(); IplI ...

  4. docker安装软件

    镜像相关命令 1.搜索镜像 # docker search java 可使用 docker search命令搜索存放在 Docker Hub(这是docker官方提供的存放所有docker镜像软件的地 ...

  5. 关于vue-resource 转变成axios的过程

    在做东钿贷后系统的时候,我选择了vue-resource这个插件作为与服务器沟通工具,但是听说前端同行说vuejs2.0已经不在维护vue-resource了,vuejs2.0 已经使用了axios了 ...

  6. 以后要进行数据收集,打开邮箱就行了 | formtalk入驻Office 应用商店

    『数据收集』,作为一项工作,存在感高的忽视不了——不管你在企业里是什么角色(大部分),Ta似乎都在你的工作范围内. 你是人事:收集招聘数据.员工信息: 你是采购:收集供应商信息.商品数据: 你是市场: ...

  7. 数据库之游标过程-- 基于MySQL

    实例如下: DROP PROCEDURE IF EXISTS pr_change_station_user_acct_his; -- 如果存在存储过程,即删除存储过程 create procedure ...

  8. html 之table标签结构学习

    一.HTML table标签结构 html 中table标签的结构情况,如下所示: <!-- table标签结构如下: <table> <thead> # thead表格 ...

  9. LIBCD.lib(crt0.obj) : error LNK2001: unresolved external symbol _main

    在创建MFC项目时,如果没有设置好项目参数, 就会在编译时产生很多连接错误, 如我今天遇到的: LIBCD.lib(crt0.obj) : error LNK2001: unresolved exte ...

  10. 11g 新特性 Member Kill Escalation 简介

    首先我们介绍一下历史.在oracle 9i/10g 中,如果一个数据库实例需要驱逐(evict, alert 文件中会出现ora-29740错误)另一个实例时,需要通过LMON进程在控制文件(以下简称 ...