返回

深入剖析LeetCode 2354:揭秘卓越二元组的奥妙(Python)

后端

算法思想

LeetCode 2354的本质是要计算数组中满足一定条件的二元组数量。这种类型的题目通常可以采用以下步骤来解决:

  1. 定义满足条件的标准 :根据题意,我们需要找到一对数字,它们在二进制表示下具有相同的最高有效位和相同数量的1。
  2. 计算满足条件的二元组数量 :我们可以使用位运算来计算每个数字在二进制表示下最高有效位的位置和1的个数。然后,我们可以使用计数器来统计满足条件的二元组数量。
  3. 优化算法 :我们可以使用一些优化技巧来减少计算时间。例如,我们可以使用位掩码来快速确定两个数字的最高有效位是否相同。

Python实现

def countExcellentPairs(nums):
  """
  :type nums: List[int]
  :rtype: int
  """
  # Initialize a dictionary to store the count of each highest significant bit (MSB) and the count of 1s.
  counts = {}

  # Initialize a counter to store the total number of excellent pairs.
  excellent_pairs = 0

  # Iterate over the array.
  for num in nums:
    # Calculate the highest significant bit (MSB) and the count of 1s.
    msb = 0
    count_ones = 0
    while num > 0:
      if num % 2 == 1:
        count_ones += 1
      msb = max(msb, count_ones)
      num //= 2

    # Update the counts in the dictionary.
    if msb not in counts:
      counts[msb] = 0
    counts[msb] += 1

  # Iterate over the dictionary.
  for msb in counts:
    # Calculate the number of excellent pairs for this MSB.
    count_pairs = counts[msb] * (counts[msb] - 1) // 2

    # Add the number of excellent pairs to the total count.
    excellent_pairs += count_pairs

  # Return the total number of excellent pairs.
  return excellent_pairs

复杂度分析

  • 时间复杂度:O(n log n),其中n是数组的长度。
  • 空间复杂度:O(n),其中n是数组的长度。

总结

LeetCode 2354是一道具有挑战性的题目,但通过深入理解算法思想和使用有效的Python实现,我们可以轻松解决这道难题。这道题不仅考察了我们对位运算计算的理解,还考验了我们使用计数器来统计满足条件的二元组数量的能力。希望这篇文章对您有所帮助!