【问题标题】:Find the Duplicate Number查找重复号码
【发布时间】:2017-03-03 05:12:44
【问题描述】:

给定一个包含 n + 1 个整数的数组 nums,其中每个整数都介于 1 和 n(含)之间,证明至少存在一个重复数。假设只有一个重复号码,找到重复号码。

我的解决方案:

def findDuplicate(nums):
    slow = fast = finder = 0
    while fast is not None:


        slow = nums[slow]
        fast = nums[nums[fast]]

        if fast is slow:
            return slow

   return False

nums = [1,2,2,3,4]
print findDuplicate(nums)

我的上述解决方案有效并给了我 o/p 2 但它不适用于每个输入,例如它不适用于 [11,15,17,17,14][3,1,2,6,2,3] 并给我错误 IndexError: list index out of range。我无法找到模式,也无法找到确切的问题。还试图改变我的 while 条件:

while fast is not None and nums[nums[fast]] is not None:

您的帮助将不胜感激!谢谢。

【问题讨论】:

  • 你想要的输出是什么
  • 我相信您的第一个示例[11,15,17,17,14] 不满足您对问题的描述:列表包含5 元素,但这些元素不在1 和5 - 1 = 4 之间。对于第二个示例[3,1,2,6,2,3],请注意 Python 的列表是 0 索引的,因此 6 是越界的。也就是说,你有一个错误。
  • 我相信通常的解决方案是对数组进行排序,然后查找两个相邻的相等值。给定约束并排序后,每个索引处的值应为 index+1。一旦你找到一个不存在的值,你就找到了该对的一个实例。另一个实例将位于前一个索引处。
  • 不幸的是,我不得不说您的代码与给定的任务无关。除了return slow 之外,函数中的每一行基本上都有问题。我建议重新开始并重新考虑您的方法。
  • Find duplicate element in array in time O(n) 的可能重复项。您尝试采用的方法是“周期检测”方法。上面的代码可能看起来有点奇怪,但它正朝着占用O(n)O(1) 空间的解决方案走上正轨。请参阅here 以获得针对此问题提供完整 Python 解决方案的答案。

标签: python


【解决方案1】:

由于数字介于 1 和 n 之间,并且您被告知只有一个重复项,因此您可以使用数组中数字之和与 1 到 n 之间的数字之和之间的差来获得副本。

def findDuplicate(l):
    n = len(l) - 1                     # Get n as length of list - 1
    return sum(l) - (n * (n + 1) / 2)  # n*(n+1)/2 is the sum of integers from 1 to n

所以重复项是列表的总和 - n*(n+1)/2

当然,这并不适用于为任何列表查找重复项。对于这种情况,您需要使用 @Jalepeno112 的答案。

【讨论】:

    【解决方案2】:

    第一个有效的事实是侥幸。让我们看看它在第一遍时的作用。

    nums = [1,2,2,3,4]
    # slow starts as index 0.  So now, you've reassigned slow to be nums[0] which is 1.
    # so slow equals 1
    slow = nums[slow]
    
    # now you are saying that fast equals nums[nums[0]].  
    # nums[0] is 1.  nums[1] is 2
    # so fast = 2        
    fast = nums[nums[fast]]
    

    在下一次通过时,slow 将是 nums[1],即 2。fast 将是 nums[nums[2]],即 nums[2],即 2。此时 slowfast 相等。

    在你的第二个例子中,你得到一个IndexError 因为fast = nums[nums[fast]] 如果nums[fast] 的值不是一个有效的索引,那么这个代码将失败。特别是在第二个示例中,nums[0] 是 11。nums 在索引 11 处没有元素,因此会出现错误。

    你真正想做的是在数组上执行一个嵌套的 for 循环:

    # range(0,len(nums)-1) will give a list of numbers from [0, to the length of nums-1)
    # range(1, len(nums)) does the same, 
    # except it will start at 1 more than i is currently at (the next element in the array).  
    # So it's range is recomputed on each outer loop to be [i+1, length of nums)
    for i in range(0,len(nums)-1):
       for j in range(i+1,len(nums)):
           # if we find a matching element, return it
           if nums[i] == nums[j]:
               return nums[i]
    # if we don't find anything return False
    return False 
    

    可能还有其他更 Pythonic 的方法可以实现这一点,但这不是您最初的问题。

    【讨论】:

    • 需要稍作修正 - 应该是 if nums[i] == num[j]:
    • 该死的。很好的收获。
    【解决方案3】:

    首先您必须确保列表中的所有数字都满足您的限制条件。

    在列表中查找重复的数字在collections 中使用Counter 它将返回每个数字和出现次数示例:

    >>> from collections import Counter
    >>> l=Counter([11,15,17,17,14])
    >>> l
    Counter({17: 2, 11: 1, 14: 1, 15: 1})
    

    获得最常见的一种用途:

    >>> l.most_common(n=1)
    [(17, 2)]
    

    其中 n 是您想要获得的最常见的数字

    【讨论】:

      【解决方案4】:
      def duplicates(num_list):
          if type(num_list) is not list:
              print('No list provided')
                  return
          if len(num_list) is 0 or len(num_list) is 1:
              print('No duplicates')
                  return
          for index,numA in enumerate(num_list):
              num_len = len(num_list)
                  for indexB in range(index+1, num_len):
                      if numA == num_list[indexB]:
                          print('Duplicate Number:'+str(numA))
                              return
      duplicates([11,15,17,17,14])
      duplicates([3,1,2,6,2,3])
      duplicates([])
      duplicates([5])
      

      【讨论】:

        【解决方案5】:
        l=[]
        n= int(input("the number of digit is :"))
        l=[0 for k in range(n)]
        for j in range(0,n):
          l[j]=int(input("the component is"))
        print(l)
        b=0;  c=0
        for i in range(n):
         if l[i]== l[n-1-i]:
            b=1;c=i
        if b==1:
         print("duplicate found! it is",l[c])
        elif b==0:
         print("no duplicate")
        

        【讨论】:

        • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-02-20
        • 1970-01-01
        • 2016-02-21
        • 1970-01-01
        • 2018-10-31
        • 2011-05-18
        • 2016-02-12
        相关资源
        最近更新 更多