Find the Duplicate Number
2015-10-28 17:56
316 查看
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个整数,其范围都在1~n之间,想象数轴上有个区间是[1,n],区间中间的数字为mid, 判断原n+1个数字,落在区间[1,mid]之间的数字总共有多少个,计为count;由于数字全部都是整数,那么[1,mid]这个区间最多能够容纳的不同整数为mid个,因为count个数字都是在[1,mid]之间的,如果说count比mid还要大,说明count个数字中肯定有重复的。这样就可以将区间折半,接下来的就在区间[1,mid]中去找重复的数字,同样的查找过程也可以将区间折半。。
实际上这n+1个数字在区间[1,n]上有整数落点,这个题目就是求在[1,n]之间哪个数字上落点是重复的,在上述将区间折半的过程中,最后一定是向那个重复落点的地方一步步逼近。
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个整数,其范围都在1~n之间,想象数轴上有个区间是[1,n],区间中间的数字为mid, 判断原n+1个数字,落在区间[1,mid]之间的数字总共有多少个,计为count;由于数字全部都是整数,那么[1,mid]这个区间最多能够容纳的不同整数为mid个,因为count个数字都是在[1,mid]之间的,如果说count比mid还要大,说明count个数字中肯定有重复的。这样就可以将区间折半,接下来的就在区间[1,mid]中去找重复的数字,同样的查找过程也可以将区间折半。。
实际上这n+1个数字在区间[1,n]上有整数落点,这个题目就是求在[1,n]之间哪个数字上落点是重复的,在上述将区间折半的过程中,最后一定是向那个重复落点的地方一步步逼近。
public class Solution { public int findDuplicate(int[] nums) { int n=nums.length; if(n==0) return -1; int left=1; int right=nums.length-1; while(left<=right) { int mid=left+(right-left)/2; int count=0; for(int i=0;i<nums.length;i++) { if(nums[i]<=mid) count++; } if(count<=mid) { left=mid+1; } else right=mid-1; } return left; } }
相关文章推荐
- java-多线程锁机制
- 清浮动方法
- 不用代码设置 切圆角
- <<JavaScript编程全解>>阅读笔记之函数与闭包
- 关于AlertDialog的自定义样式
- Spring-Loaded使用小记
- KVC 与 KVO 理解
- table标签的属性
- mybatis 传递set集合
- 华为面试题 题目:有两个数组a,b,大小都为n,数组元素的值任意,无序; 要求:通过交换a,b中的元素,使数组a元素的和与数组b元素的和之间的差最小
- leetcode 202 Happy Number
- 常用经典java代码集锦
- http断点续传原理:http头 Range、Content-Range
- JAVA多线程之Thread VS Runnable
- 详解jsonp的实现
- 更快、更强——解析Hadoop新一代MapReduce框架Yarn
- H264中的SPS、PPS提取与作用
- ftp 不识别中文/传送中文文件失败的原因和解决方案
- QQ截图问题——如何截取活动的弹出菜单
- 通过Gradle实现多渠道打包