Find The Duplicate Number
来源:互联网 发布:连通区域图像分割算法 编辑:程序博客网 时间:2024/06/05 02:44
题目描述
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.
题目解答
题目分析
二分查找
1…10, 小于等于5的一定有5个,如果多于5个,就在lower part, 等于5个就是upper part.
代码实现
public class Solution { public int findDuplicate(int[] nums) { if(nums == null || nums.length == 0) return 0; int len = nums.length; int low = 1, high = len - 1; while(low < high) { int middle = (low + high) / 2; int count = counts(nums, middle, len); if(count > middle) high = middle; else low = middle + 1; } return low; } public int counts(int[] nums, int middle, int len) { int ret = 0; for(int i = 0; i < len; i++) { if(nums[i] <= middle) ret++; } return ret; }}
0 0
- Find the Duplicate Number
- Find the Duplicate Number
- Find the Duplicate Number
- Find the Duplicate Number
- Find the Duplicate Number
- Find the Duplicate Number
- Find the Duplicate Number
- Find the Duplicate Number
- Find the Duplicate Number
- Find the Duplicate Number
- Find the Duplicate Number
- Find The Duplicate Number
- Find the Duplicate Number
- Find the Duplicate Number
- Find the Duplicate Number
- Find the Duplicate Number
- Find the Duplicate Number
- Find the Duplicate Number
- C# Func的介绍
- QT5串口通信
- Android WebView关于图片/文件上传
- Android四大组件Broadcast Receiver详解
- 【图论】单源点最短路模板(有向图)Dijkstra
- Find The Duplicate Number
- python 一个简单的依靠文件来判断key是否重复的方法
- 深入研究java.lang.Object类
- Linux 的启动流程
- 1063. Set Similarity (25) 并查集
- kafka学习教程
- curl,用法實例
- 正则表达式相关网址
- iOS新方法systemFontOfSize: weight: