【问题标题】:Finding the only unique value in a list [duplicate]查找列表中唯一的唯一值[重复]
【发布时间】:2021-08-28 02:21:46
【问题描述】:

我正在参加一项 Codewars 挑战,以寻找列表中的唯一值,但我无法以我的技能水平找到完成此过程的好方法。

此解决方案适用于测试,但尝试超时(12000 毫秒)。

def find_uniq(arr):
    for element in arr:
        if arr.count(element) == 1:
            return element

练习链接: https://www.codewars.com/kata/585d7d5adb20cf33cb000235/train/python

【问题讨论】:

标签: python


【解决方案1】:

您的算法是 O(n^2),其中 n 是数组元素的数量。您应该考虑使用dictcollections.Counter

# Not tested
def findUnique(arr):
  from collections import Counter
  counter = Counter(arr)
  for value, count in counter.items():
    if count == 1:
      return value

【讨论】:

    【解决方案2】:

    一个简单的方法是跟踪每个项目的计数。

    from collections import Counter
    
    def find_uniq(arr):
        # Count each item.
        # I suggest you try to write your own Counter as an exercise.
        # You will need to loop over the entire array.
        # Store your results in a dict.
        counts = Counter(arr)
    
        # Now, loop over the resulting counts and check which item has a count of 1.
        for value, count in counts.items():
            if count == 1:
                return value
    
        raise ValueError("Could not find unique item!")
    

    【讨论】:

      【解决方案3】:

      基于相邻元素排序和检查的解决方案

      def find_uniq(arr: list):
          arr.sort()
          n = len(arr) - 1
          for i, x in enumerate(arr):
              if (i == n or x != arr[i + 1]) and (
                      i == 0 or x != arr[i - 1]):  # if there are no identical neighboring elements
                  return x
          return None
      
      print(find_uniq([10, 10, 10, 1, 1, 1, 1, 1, 100, 2, 2, 2, 2, 3, 3, 3, 3, 7, 7, 7, 7, 8, 8, 8, 8]))
      

      打印:

      100
      

      【讨论】:

      • 这有效,我认为我修改后的代码会有效,但它也会超时。是时候多上课了,谢谢
      猜你喜欢
      • 1970-01-01
      • 2011-04-22
      • 1970-01-01
      • 2018-01-05
      • 2021-01-23
      • 1970-01-01
      • 2019-04-22
      • 2016-09-29
      • 2022-06-23
      相关资源
      最近更新 更多