Find the Duplicate Number
2016-03-04 01:16
351 查看
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
There is only one duplicate number in the array, but it could be repeated more than once.
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.
class Solution { public: int findDuplicate(vector<int>& nums) { int n = nums.size(); int left = 1; int right = n-1; while (left < right-1) { int mid = left + (right-left)/2; int count = 0; for (int i = 0; i < n; i++) { if (nums[i] <= mid) { count++; } } if (count <= mid) { left = mid; } else { right = mid; } } int count = 0; for (int i = 0; i < n; i++) { if (nums[i] == left) { count++; } } if (count > 1) { return left; } return right; } };
相关文章推荐
- 支付宝账户提现的银行账户已经被占用了怎么办
- 学习新东西的唯一方法
- 旋转数组的最小数字
- 康子KAKA 程序猿毕业后荒唐的两年点滴
- CSS实现Loading加载动画
- Mac快捷键
- Elasticsearch v2.2 快速入门(含curl,Sense,python 3种客户端方式)
- cocos2dx Action 特效
- 支付宝认证银行卡丢失了,怎么办
- android 图片转 Base64
- i++与++i的误解
- SQLAlchemy 学习笔记
- 软件工程与个人项目的结合
- CSS学习(六)-css圆角边框高级效果、边框阴影效果(上)
- 推荐几款实用的Android Studio 插件
- read me of del.sh
- div在各种情况下的居中
- C++栈(stack)
- del.sh
- 学习软件设计模式的书籍