LeetCode 题解(252) : Find the Duplicate Number
来源:互联网 发布:nginx tcp代理 编辑:程序博客网 时间:2024/04/29 11:13
题目:
Given an array nums containing n + 1 integers where each integer is between 1 andn (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.
这道题太高深了,参见这里的解法
C++版:
class Solution {public: int findDuplicate(vector<int>& nums) { int low = 0, high = nums.size() - 1; while(low <= high) { int mid = (low + high) / 2; int count = 0; for(int i = 0; i < nums.size(); i++) { if(nums[i] <= mid) count++; } if(count > mid) high = mid - 1; else low = mid + 1; } return low; }};
Python版:
class Solution(object): def findDuplicate(self, nums): """ :type nums: List[int] :rtype: int """ low, high = 0, len(nums) - 1 while low <= high: mid = (low + high) / 2 cnt = sum(x <= mid for x in nums) if cnt > mid: high = mid - 1 else: low = mid + 1 return low
0 0
- LeetCode 题解(252) : Find the Duplicate Number
- Leetcode题解 287. Find the Duplicate Number
- leetcode题解-287. Find the Duplicate Number
- LeetCode 287. Find the Duplicate Number 题解(C++)
- LeetCode题解(Week 1):287. Find the Duplicate Number
- leetcode Find the Duplicate Number
- *LeetCode-Find the Duplicate Number
- [Leetcode] Find the Duplicate Number
- Leetcode -- Find the Duplicate Number
- LeetCode----Find the Duplicate Number
- LeetCode Find the Duplicate Number
- LeetCode -- Find the Duplicate Number
- [Leetcode]Find the Duplicate Number
- leetcode Find the Duplicate Number
- 【Leetcode】Find the Duplicate Number
- LeetCode Find the Duplicate Number
- Leetcode: Find the Duplicate Number
- leetcode: Find the Duplicate Number
- 二、微信企业号开发:corpsecret到底在哪块呢
- SWT布局
- Active Learning 主动学习
- linux下dns设置详解
- 代理模式深入学习(一)——动态代理的实现及解析
- LeetCode 题解(252) : Find the Duplicate Number
- 四大配置管理工具测评手记
- JAVA8函数式编程
- 手势识别——GestureDetector
- 简单自动补全(js+css)
- 九月英语总结——不同凡响
- 基于注解的 Spring MVC 简单入门
- CF 581F 树形dp
- activity生命周期