zoukankan      html  css  js  c++  java
  • leetcode287 Find the Duplicate Number

     1 """
     2 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.
     3 Example 1:
     4 Input: [1,3,4,2,2]
     5 Output: 2
     6 Example 2:
     7 Input: [3,1,3,4,2]
     8 Output: 3
     9 """
    10 """
    11 解法一:
    12 这道题竟然可以用快慢指针法!!!
    13 与leetcode142类似。https://www.cnblogs.com/yawenw/p/12324170.html
    14 因此找环 找重复值 都可以考虑用快慢指针法
    15 """
    16 class Solution1:
    17     def findDuplicate(self, nums):
    18         if not nums:
    19             return -1
    20         slow = nums[0]
    21         fast = nums[nums[0]]
    22         while slow != fast:
    23             slow = nums[slow]
    24             fast = nums[nums[fast]]
    25         fast = 0
    26         while slow != fast:
    27             fast = nums[fast]
    28             slow = nums[slow]
    29         return slow
    30 
    31 """
    32 解法二:时间复杂度高的解法
    33 """
    34 class Solution2:
    35     def findDuplicate(self, nums):
    36         for i in range(len(nums)):
    37             if nums[i] in nums[i+1:]:
    38                 return nums[i]
  • 相关阅读:
    滑动窗口算法-2
    滑动窗口算法-1
    工作中缓存使用重点
    QPS的计算方法[转载]
    springAop
    spring配置详述与springboot
    LRU最少使用
    图片压缩
    Javassist使用[转载]
    [转]关于Spring事务嵌套回滚的一些测试总结
  • 原文地址:https://www.cnblogs.com/yawenw/p/12432029.html
Copyright © 2011-2022 走看看