You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python优化CountMultiplicativePairs求解及复杂度优化问询

CountMultiplicativePairs问题优化需求

我需要解决CountMultiplicativePairs问题:统计满足x*y ≥ x+y的数对(x,y)。目前实现的Python代码时间复杂度为O(n²),希望得到更高效的优化解法;现有C#解法逻辑复杂且缺乏清晰说明,附上我的Python实现代码:

def solution(A,B):
    """
    Count the number of pairs (x, y) such that x * y >= x + y. 
    """
    M = 1000*1000
    max_count=1000*1000*1000
    zero=count=0
    if len(A)<=1:
        return "Length of array A should be greater than 1"
    if len(B)<=1:
        return "Length of array B should be greater than 1"
    if len(A)!=len(B):
        return "Length of both arrays should be equal"
    C=[0]*len(A)
    for (i, elem) in enumerate(A):
        C[i]=float(A[i])+float(B[i]/M)
    for (i, elem) in enumerate(C):
        if elem==0:
            zero+=1
            
        if elem>0 and elem<=1:
            pass
        if elem>1:
            for j in range(i+1,len(C)):
                if round(C[i]*C[j],2)>=C[i]+C[j]:
                    count+=1
    zero_pairs=int(zero*(zero-1)/2)
    count+=zero_pairs
    return min(count,max_count)

# 测试用例
#print(solution([0,1,2,2,3,5], [500000, 500000, 0, 0, 0, 20000]))
print(solution([1, 1, 1, 2, 2, 3, 5, 6],[200000, 250000, 500000, 0, 0, 0, 0, 0]))

# print(solution([0, 0, 2, 2], [0, 0, 0, 0]))
# print(solution([1, 3], [500000, 10000]))
# print(solution([1, 3], [400000, 500000]))
#print(solution([0, 0, 0, 0] , [0, 0, 0, 0]))
#print(solution([0, 0, 0, 0] , [1, 1, 1, 1]))

核心诉求

  • 优化现有O(n²)时间复杂度的代码,实现更高效的算法(如O(n log n)级别)
  • 提供清晰的优化思路或可运行的高效实现方案

内容的提问来源于stack exchange,提问作者Rakshita Shetty

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 10:25:18