leetcode#287. Find the Duplicate Number
来源:互联网 发布:java服务器用linux 编辑:程序博客网 时间:2024/06/16 19:14
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:
- 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(n^2).
- There is only one duplicate number in the array, but it could be repeated more than once.
Code
class Solution: def findDuplicate(self, nums): """ :type nums: List[int] :rtype: int """ Min, Max = 1, len(nums) - 1 return self.find(nums, Min, Max) def find(self, nums, Min, Max): while Min <= Max: mid = (Min + Max) // 2 small = big = isMid = 0 for i in nums: if i == mid: isMid += 1 if isMid == 2: return mid elif i > mid and i <= Max: big += 1 elif i >= Min and i < mid: small += 1 if small > big: Max = mid - 1 elif small < big: Min = mid + 1 else: return self.find(nums, Min, mid - 1) or self.find(nums, mid + 1, Max) return False
题目要求了时间复杂度和空间复杂度,那么我想到的也就是这个方法了,不断缩小检索的范围,直至找到重复的值。这个算法的时间复杂度应该是n*logn。
阅读全文
0 0
- [leetcode] 287.Find the Duplicate Number
- [leetcode] 287. Find the Duplicate Number
- <LeetCode OJ> 287. Find the Duplicate Number
- Leetcode 287. Find the Duplicate Number
- Leetcode - 287. Find the Duplicate Number
- [LeetCode]287. Find the Duplicate Number
- LeetCode 287. Find the Duplicate Number
- 【leetcode】287. Find the Duplicate Number
- 【leetcode】287. Find the Duplicate Number
- leetcode 287. Find the Duplicate Number
- LCP287 LeetCode 287. Find the Duplicate Number
- [Leetcode]287. Find the Duplicate Number
- Leetcode题解 287. Find the Duplicate Number
- [LEETCODE] 287. Find the Duplicate Number
- [LeetCode] 287. Find the Duplicate Number
- <leetcode>287. Find the Duplicate Number
- [leetcode]287.Find the Duplicate Number
- LeetCode 287. Find the Duplicate Number
- java循环语句
- 山东大学java程序设计实验报告6数组
- mybatis总结1
- Python 列表
- spring总结
- leetcode#287. Find the Duplicate Number
- viewport 缩放
- 记录一些我开发经常用的东西
- Ubuntu 16.04 LTS官方镜像
- 欢迎使用CSDN-markdown编辑器
- 建造者模式
- static 的作用
- Java -Tomcat 之 Mac下配置Intellij IDEA + Tomcat 权限问题
- [OpenJudge] 2727 仙岛寻药