[英]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.