2. 447. 回旋镖的数量
这个题目竟然没做出来。。醉了,确实还是没想到用hash空间代替时间的思路
def dis(self,p1,p2):
return (p1[0]-p2[0])**2 + (p1[1]-p2[1])**2
def numberOfBoomerangs(self, points: List[List[int]]) -> int:
ans = 0
for i in points:
dic = {}
for j in points:
if j != i:
d = self.dis(i,j)
dic[d] = dic.get(d,0) + 1
for k,v in dic.items():
ans += v*(v-1)
return ans
不用counter感觉还是可以省一些时间的 用dict的get方法就行
这里不得不想一下查找表推荐的3中数据结构 : set dict map
遍历时多用索引,而不要直接用值进行遍历;
3. 149. 直线上最多的点数
其实已经做出来了,就是有个例子过不去,为什么呢,是因为浮点数的问题
官方应该是把测试用例升级了
比如 52/51 和 51/50 一定不同的
但是 92119952/92119952 和 92119951/92119950 就相同了,
可以看下这个博客
最后引入decimal解决问题,但是其他方面好像自己写的有点繁琐了,可以优化一下
def maxPoints(self, points: List[List[int]]) -> int:
from decimal import Decimal
if len(points) < 3:
return len(points)
ans = 0
dic_init = {}
for point in points:
key = str(point[0]) + ',' + str(point[1])
dic_init[key] = dic_init.get(key,0) + 1
arr = list(dic_init.keys())
if len(arr) == 1:
return dic_init[arr[0]]
for i in arr:
dic = {}
posi = i.split(',')
xi = (int)(posi[0])
yi = (int)(posi[1])
for j in arr:
if j != i:
posj = j.split(',')
xj = (int)(posj[0])
yj = (int)(posj[1])
x_dis = Decimal(xj - xi) #主要是这里要用decimal
y_dis = Decimal(yj - yi) #
key = 'inf' if x_dis == 0 else y_dis / x_dis
if(dic.get(key,0) == 0):
dic[key] = dic_init[i] + dic_init[j]
else:
dic[key] += dic_init[j]
l = sorted(dic.items(), key=lambda x:x[1],reverse=True)
tmp_max = l[0][1]
ans = max(ans,tmp_max)
return ans
下面是修改之后的版本,但是没有我的快,而且这两个的性能都不好,我估计是之前的人们没有那个新加的测试用例,所以各种过
def maxPoints(self,points):
if len(points) < 3:
return len(points)
res = 0
from collections import defaultdict
for i in range(len(points)):
record = defaultdict(int)
samepoint = 0
for j in range(len(points)):
if points[i][0] == points[j][0] and points[i][1] == points[j][1]:
samepoint += 1
else:
record[self.get_Slope(points,i,j)] += 1
for v in record.values():
res = max(res, v+samepoint)
res = max(res, samepoint)
return res
def get_Slope(self,points,i,j):
from decimal import Decimal
if points[i][1] - points[j][1] == 0:
return float('Inf')
else:
return Decimal(points[i][0] - points[j][0]) / Decimal(points[i][1] - points[j][1])
网友评论