簡體   English   中英

得到缺少的矩形點? 如何降低此代碼的時間復雜度?

[英]get Missing Rectangle Point ? How can i reduce the time complexity of this code?

這里我寫了代碼從矩形的坐標中找到矩形的缺失坐標。

def getMissingRectanglePoint(rectangle):
    list1=[]
    list2=[]
    for  i in rectangle:
        list1.append(i[0])
        list2.append(i[1])
    x=None
    y=None
    for i in list1:
        if(list1.count(i) % 2):
            x=i 
            break
    for i in list2:
        if(list2.count(i) % 2):
            y=i
            break

    return [x,y]
    

no_of_testcases=int(input())

for i in range(0,no_of_testcases):
    
    no_of_rectangles=int(input())
    cordinates=[]
    
    for i in range(0,(4*no_of_rectangles-1)):
        
        cordinates.append(list(input().split(" ")))
        
    cord1=getMissingRectanglePoint(cordinates)
    
    print(cord1[0],cord1[1])

這是根據代碼的輸入:

1
2
1 1
1 2
4 6
2 1
9 6
9 3
4 3

而這個的o / p是:

2,2

建議減少執行此代碼所需時間的最佳方法。

您多次掃描列表以查找每個值。 相反,您可以使用字典方法計算每個坐標值的出現。

import collections
def getMissingRectanglePoint(coords):
    dx = collections.Counter()
    dy = collections.Counter()
    for coord in coords:
        dx[coord[0]] += 1
        dy[coord[1]] += 1
    for xx in dx:
        if dx[xx] % 2 == 1:
            mx = xx
            break
    for yy in dy:
        if dy[yy] % 2 == 1:
            my = yy
            break
    return [mx, my]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM