传送门

Description

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.

思路

题意:给定一个数组,包含n + 1个数,其数值在1-n之间,证明至少存在一个重复的数。假设仅有一个重复的数,找出它。

要求:

  • 假设数组仅为可读,不允许改变数组
  • 空间复杂度为O(1),时间复杂度要求小于O(n2)

题解:由于不允许改变数组,因此不能将数组排序,又因为额外的空间仅允许O(1),因此,不考虑hash。复杂度不能为O(n2),所以不能暴力求解。

方法一:为了降低复杂度,我们可以考虑二分,将复杂度降低为O(nlogn),每次二分,然后遍历数组,查看小于等于mid的数,如果个数小于等于mid,则证明重复的数小于等于mid,反之在[mid + 1,right]的区间。

方法二:此种方法利用floyd判圈算法的原理来求解,具体可以查看这里:click here

class Solution {
public:
//9ms
int findDuplicate(vector<int>& nums) {
if (nums.size() > ){
int slow = nums[],fast = nums[nums[]];
while (slow != fast){
slow = nums[slow];
fast = nums[nums[fast]];
}
fast = ;
while (slow != fast){
slow = nums[slow];
fast = nums[fast];
}
return slow;
}
return -;
} //9ms
int findDuplicate(vector<int>& nums) {
int left = ,right = nums.size() - ;
while (left < right - ){
int mid = left + ((right - left) >> );
int cnt = ;
for (auto val : nums){
if (val <= mid) cnt++;
}
if (cnt <= mid) left = mid;
else right = mid;
}
return left;
}
};

最新文章

  1. 【BZOJ-1656】The Grove 树木 BFS + 射线法
  2. css设置背景图片
  3. sqlite的ef使用小结
  4. 如何让电脑公司Win7系统自动关闭停止响应的程序
  5. SCI/EI期刊投稿 Reply Letter 常用格式总结
  6. HDU 1565&amp;1569 方格取数系列(状压DP或者最大流)
  7. ExecuteNonQuery()返回值注意点
  8. python(五)图形用户界面easyGUI入门
  9. WCF 配置服务 (02)
  10. tyvj1728 普通平衡树
  11. 基于Nodejs开发的web即时聊天工具
  12. ASPxGridView-为每行添加序号
  13. Cocos-2dx-Lua中使用Luaj的完整示例(转)
  14. 自动化测试(二) 单元测试junit的Test注解突然不能使用原因以及解决方案
  15. Java中的String类型
  16. Git协同工作流介绍
  17. react组件传值传方法
  18. fluxion-wifi破解/钓鱼
  19. 《坦克世界》1.0+:使用 CPU 优化的图形和物理丰富用户体验
  20. SQL 常用判断语句

热门文章

  1. JavaScript之基础语法
  2. Android客户端与Python服务器端的简单通信
  3. JavaScript——call() 方法
  4. 没有找到&lt;context:component-scan base-package=&quot;&quot;&gt;标签
  5. 查看Xcode里的描述文件
  6. SVG 学学就会了。
  7. 了解Greenplum(1)
  8. LNMP集群架构篇
  9. 13DBUtils工具类
  10. VUE的系统指令