Leetcode刷题第二天
下午还有一场商汤面试和明天的blue面试
leetcode刷了两题????
一、今天刷的题目是
这道题目难度等级是困难(捂脸),因为昨天面试出的就是这个题目,所以我拿过来做一做
我写的代码如下:
class Solution:
def maxPoints(self, points):
b=[]
a=dict()
lens=len(points)
for i in range(lens):
a.clear()
a[999]=1
for j in range(i+1,lens):
if points[i][0]==points[j][0]:
a[999]+=1
else:
if (points[i][1]-points[j][1])/(points[i][0]-points[j][0]) in a.keys():
a[(points[i][1]-points[j][1])/(points[i][0]-points[j][0])]+=1
else:
a[(points[i][1]-points[j][1])/(points[i][0]-points[j][0])]=2
b.append(max(list(a.values())))
return max(b)
w=Solution().maxPoints([[1,1],[3,2],[5,3],[4,1],[2,3],[1,4]])
这里考虑了斜率无穷大(999)的情况
也可以将分数表示作为我们的键名
from fractions import Fraction
if Fraction((points[i][1]-points[j][1]),(points[i][0]-points[j][0])) in a.keys():
思想主要是:
①A,B,C,D假设四个点,先让A,B; A,C; A,D求斜率,并且将它们存在字典里面,字典的key表示斜率,value表示在一条线上的点数;
遍历dict的key,没有这个斜率,则添加一个键值对;如果有,就在原来的value上加1.
在一轮i值的循环(让A,B; A,C; A,D求斜率)中,我们求出在一条直线的最大点数,并append到一个空列表中
然后②
在第二轮i值的循环中(让B,C;B,D求斜率),然后还是和上面一样的操作
最后求出那个储存着每一轮最大点数的list的最大值
实验结果分析:
官方答案中给出的代码如下:
import matplotlib.pyplot as plt
class Solution(object):
def maxPoints(self, points):
"""
:type points: List[List[int]]
:rtype: int
"""
def max_points_on_a_line_containing_point_i(i):
"""
Compute the max number of points
for a line containing point i.
"""
def add_line(i, j, count, duplicates):
"""
Add a line passing through i and j points.
Update max number of points on a line containing point i.
Update a number of duplicates of i point.
"""
# rewrite points as coordinates
x1 = points[i][0]
y1 = points[i][1]
x2 = points[j][0]
y2 = points[j][1]
# add a duplicate point
if x1 == x2 and y1 == y2:
duplicates += 1
# add a horisontal line : y = const
elif y1 == y2:
nonlocal horisontal_lines
horisontal_lines += 1
count = max(horisontal_lines, count)
# add a line : x = slope * y + c
# only slope is needed for a hash-map
# since we always start from the same point
else:
slope = (x1 - x2) / (y1 - y2)
lines[slope] = lines.get(slope, 1) + 1
count = max(lines[slope], count)
return count, duplicates
# init lines passing through point i
lines, horisontal_lines = {}, 1
# One starts with just one point on a line : point i.
count = 1
# There is no duplicates of a point i so far.
duplicates = 0
# Compute lines passing through point i (fixed)
# and point j (interation).
# Update in a loop the number of points on a line
# and the number of duplicates of point i.
for j in range(i + 1, n):
count, duplicates = add_line(i, j, count, duplicates)
return count + duplicates
# If the number of points is less than 3
# they are all on the same line.
n = len(points)
if n < 3:
return n
max_count = 1
# Compute in a loop a max number of points
# on a line containing point i.
for i in range(n - 1):
max_count = max(max_points_on_a_line_containing_point_i(i), max_count)
return max_count
我还没看,但是它运行
Solution().maxPoints([[0,0], [94911150,94911151], [94911151,94911152]])
的时候,返回值为3,错误!!!!
用我自己的代码跑出来,结果为2(比耶)