1. 程式人生 > >演算法分析課每週練習 Max Points on a Line

演算法分析課每週練習 Max Points on a Line

關於題目的選取

FIlter By Top Interview Questions依次選取

題目

Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.

題目分析

簡單暴力的方法是直接計算任意兩點間的斜率(考慮垂直的線還有重複的點),兩層迴圈求出結果。

class Point(object):
    """Definition for a point."""
    def __init__(self, a=0, b=0):
        self.x = a
        self.y = b

class Solution(object):
    def maxPoints(self, points):
        """
        :type points: List[Point]
        :rtype: int
        """
        n = len(points)  
        if n < 3:  
            return n  
        res = -1  
        for i in range(n):  
            k = {'inf': 0}  
            duplicate = 1  
            for j in range(n):  
                if i == j:  
                    continue  
                elif points[i].x == points[j].x and points[i].y != points[j].y:  
                    k['inf'] +=1  
                elif points[i].x != points[j].x:  
                    k = 1.0 * (points[j].y - points[i].y) / (points[j].x - points[i].x)  
                    k[k] = 1 if k not in k.keys() else k[k] + 1  
                else:  
                    duplicate += 1  
            res = max(res, max(k.values()) + duplicate)  
        return res  
演算法空間複雜度O(n),時間複雜度O(n^2)

演算法改進分析

演算法實際上計算了兩次的某兩點間的斜率,因此提高程式的空間佔用可以降低運算時間

同一條線上的點的斜率,有些計算應該是冗餘的,但是難以減少。