【问题标题】:How can i reduce the complexity / time it takes to do this triplet count function?如何减少执行此三元组计数功能所需的复杂性/时间?
【发布时间】:2020-06-05 21:28:08
【问题描述】:

目前想知道如何降低这个三元组计数函数的复杂性/时间?

这个方案可行,但是传递HackerRank太慢了

def count_triplets(arr, r):
    left_map = {}
    right_map = {}
    for item in arr:
        right_map[item] = arr.count(item)  # store frequency of occurences of each item.

    count = 0
    for i in range(0, len(arr)):
        mid_term = arr[i]
        c1 = 0
        c3 = 0
        right_map[mid_term] -= 1
        left_term = mid_term / r
        if left_term in left_map and mid_term % r == 0:
            c1 = left_map.get(left_term)

        right_term = mid_term * r
        if right_term in right_map:
            c3 = right_map.get(right_term)

        count += c1 * c3

        if mid_term in left_map:
            left_map[mid_term] += 1
        else: 
            left_map[mid_term] = 1

    return count


if __name__ == '__main__':
    r = 3
    arr = [1,3,9,9,9,27,81]  # returns 9 as solution
    # arr = [1,3,9,9,27,81] # returns 6 as solution
    result = count_triplets(arr, r)
    print("result = ", result)

【问题讨论】:

  • 您将在 codereview.stackexchange.com 上为这篇文章获得更好的答案

标签: python dictionary hashtable


【解决方案1】:

这段代码:

    right_map = {}
    for item in arr:
        right_map[item] = arr.count(item)  # store frequency of occurences of each item.

是 O(n^2) 复杂度,因为 arr.count 本身就是 O(n),这可能是你的问题。您可以使用Counter 计算O(n) 中的所有项目,这通常也有助于简化您的代码:

from collections import Counter


def count_triplets(arr, r):
    left_map = Counter()
    right_map = Counter(arr)

    count = 0
    for mid_term in arr:
        right_map[mid_term] -= 1
        if mid_term % r == 0:
            left_term = mid_term / r
            c1 = left_map[left_term]
        else:
            c1 = 0

        right_term = mid_term * r
        c3 = right_map[right_term]

        count += c1 * c3
        left_map[mid_term] += 1

    return count


def test():
    r = 3
    assert count_triplets([1, 3, 9, 9, 9, 27, 81], r) == 9
    assert count_triplets([1, 3, 9, 9, 27, 81], r) == 6


if __name__ == '__main__':
    test()

【讨论】:

    猜你喜欢
    • 2021-08-15
    • 2021-08-14
    • 2021-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多