leetcode -- Find the Duplicate Number-- 经典重点

来源:互联网 发布:mac信仰灯怎么关 编辑:程序博客网 时间:2024/06/05 19:20

https://leetcode.com/problems/find-the-duplicate-number/

思路1 BS

http://bookshadow.com/weblog/2015/09/28/leetcode-find-duplicate-number/
http://www.cnblogs.com/grandyang/p/4843654.html

利用抽屉原理,在[1,2,3,4,…, n]中做BS, 求得mid,如果小于等于mid数目> mid, 那么说明在这个范围内有number 被duplicate了。所以high = mid - 1. 找到最后duplicate的那个number。注意这里low就是最后的结果,总结BS的时候再看看

class Solution(object):    def findDuplicate(self, nums):        """        :type nums: List[int]        :rtype: int        """        low, high = 1, len(nums) - 1        while low <= high:            mid = (low + high) >> 1            cnt = sum(x <= mid for x in nums)            if cnt > mid:                high = mid - 1            else:                low = mid + 1        return low

思路2 O(n)

http://bookshadow.com/weblog/2015/09/28/leetcode-find-duplicate-number/

比较难的算法。复习的时候再看看。

思路3

这里要求不改变数组,所以不能排序,或者swap。但是http://fisherlei.blogspot.hk/2015/10/leetcode-find-duplicate-number-solution.html给的思路很好,虽然不满足题意。

0 0
原创粉丝点击