内容中心

2026年评价高的热水锅炉厂家对比推荐-包头市鹿宇锅炉制造有限责任公司

To solve this problem, we need to count the number of pairs (i, j) such that i < j and the sum of the elements at these indices is divisible by 3. The key insight here is to leverage the remainders of the elements when divided by 3, as this allows us to efficiently compute the valid pairs without checking all possible pairs (which would be O(n²)).

Approach

  1. Remainder Classification: For each element in the array, compute its remainder when divided by 3. The remainders can be 0, 1, or 2.
  2. Count Remainders: Maintain counts of elements with each remainder (count0 for remainder 0, count1 for remainder 1, count2 for remainder 2).
  3. Calculate Valid Pairs:
    • Pairs of elements with remainder 0: The sum of two elements with remainder 0 is divisible by 3. The number of such pairs is given by the combination formula C(count0, 2) = count0 * (count0 - 1) // 2.
    • Pairs of elements with remainder 1 and 2: The sum of an element with remainder 1 and another with remainder 2 is divisible by 3. The number of such pairs is count1 * count2.

Solution Code

def count_pairs(arr):
    count0 = count1 = count2 = 0
    for num in arr:
        rem = num % 3
        if rem == 0:
            count0 += 1
        elif rem == 1:
            count1 += 1
        else:
            count2 += 1
    return (count0 * (count0 - 1) // 2) + (count1 * count2)

Explanation

  • Remainder Classification: By focusing on remainders, we reduce the problem to counting valid combinations of these remainders.
  • Efficiency: This approach runs in O(n) time (since we iterate through the array once) and uses O(1) space (only three variables to count remainders). This makes it suitable for large arrays.

Let’s verify with an example:

  • Input: [1, 2, 3, 4, 5, 6]
  • Remainders: 1,2,0,1,2,0 → count0=2, count1=2, count2=2.
  • Valid Pairs: (21//2) + (22) =1 +4=5 → which is correct (the valid pairs are (0,1), (0,4), (1,3), (3,4), (2,5)).

This solution efficiently computes the required result with optimal time and space complexity.

Answer: The function count_pairs as defined above returns the number of valid pairs. For example, if the input array is [1,2,3,4,5,6], the output is 5. The final answer is the code implementing this logic.

def count_pairs(arr):
    count0 = count1 = count2 = 0
    for num in arr:
        rem = num % 3
        if rem == 0:
            count0 += 1
        elif rem == 1:
            count1 += 1
        else:
            count2 += 1
    return (count0 * (count0 - 1) // 2) + (count1 * count2)

# Example usage:
# arr = [1,2,3,4,5,6]
# print(count_pairs(arr))  # Output:5

包头市鹿宇锅炉制造有限责任公司

包头市鹿宇锅炉制造有限责任公司



作者声明:本文包含人工智能生成内容。

在线客服

在线留言
您好,很高兴为您服务,可以留下您的电话或微信吗?