[LeetCode]149. Max Points on a Line
2016-11-13 23:18
387 查看
0. 问题地址
https://leetcode.com/problems/max-points-on-a-line/1. 问题简述
给定n个二位坐标点,求最多的处于同一直线的点的个数2. 解题思路
暴力。O(n*n*log(n)),记录所有点对的斜率(横坐标相同的话记为inf),记录对于一个点。求得包含此点的点对斜率出现的频次最大值,最终求得结果。3. 题解代码
class Point(object): def __init__(self, a=0, b=0): self.x = a self.y = b def get_slope(a, b): if a.x == b.x: return float('inf') return float(a.y - b.y) / (a.x - b.x) class Solution(object): def maxPoints(self, points): """ :type points: List[Point] :rtype: int """ size = len(points) # size(len) of points if size <= 2: return size pos = [1 for _ in points] # every position with same initial value 1 # handle same coordinates(same position) for i in range(0, size): if pos[i] == 0: continue for j in range(i + 1, size): if points[i].x == points[j].x and points[i].y == points[j].y: pos[i] += 1 pos[j] = 0 # mark idx [j] to 0 ans = max(pos) for i in range(0, size): if pos[i] == 0: continue slope_dict = {} for j in range(i + 1, size): if pos[j] == 0: continue slope = get_slope(points[i], points[j]) # print "(", points[i].x, ",", points[i].y, ")", "(", points[j].x, ",", points[j].y, ")", slope if slope in slope_dict: slope_dict[slope] += pos[j] else: slope_dict[slope] = pos[i] + pos[j] if slope_dict == {}: continue # print slope_dict ans = max(ans, max(slope_dict.values())) return ans if __name__ == '__main__': sol = Solution() points = [Point(84,250), Point(0,0), Point(1,0), Point(0,-70), Point(0,-70), Point(1,-1), Point(21,10), Point(42,90), Point(1, 1), Point(-42,-230), ] print sol.maxPoints(points), "is answer" # [[84,250],[0,0],[1,0],[0,-70],[0,-70],[1,-1],[21,10],[42,90],[-42,-230]] # 6 is answer
4. 速度
按理说这个做法很笨,甚至有超时可能,但是看了结果却发现是在python中最快的。相关文章推荐
- Leetcode 149. Max Points on a Line
- 【LeetCode】149. Max Points on a Line
- LeetCode149—Max Points on a Line
- LeetCode | 149. Max Points on a Line求多个点里面在一条直线上的点最多有多少个难题
- LeetCode 149. Max Points on a Line
- leetcode_149. Max Points on a Line
- Leetcode 149. Max Points on a Line
- [LeetCode]题解(python):149-Max Points on a Line
- [LeetCode]149. Max Points on a Line
- leetcode题解-149. Max Points on a Line
- 【LeetCode】149. Max Points on a Line - javascript
- leetcode 149:Max Points on a Line(java实现)细致分析
- leetcode[149]Max Points on a Line
- [leetcode] 149. Max Points on a Line 解题报告
- [LeetCode] 149. Max Points on a Line
- LeetCode 149. Max Points on a Line **** 灵活键,查找表
- [LeetCode] 149. Max Points on a Line
- leetcode 149. Max Points on a Line
- leetcode 149: Max Points on a Line
- LeetCode 149 — Max Points on a Line(C++ Java Python)