LeetCode Max Points on a Line

原题链接在这里:https://leetcode.com/problems/max-points-on-a-line/

这道题就是给你一个2D平面,然后给你的数据结构是由横纵坐标表示的点,然后看哪条直线上的点最多。

 (1)两点确定一条直线

 (2)斜率相同的点落在一条直线上

 (3)坐标相同的两个不同的点 算作2个点

利用HashMap,Key值存斜率,Value存此斜率下的点的个数。如果遇到重合的点,same来记录相同点的个数。

维护一个localmax,计算当前情况下的最大值;再维护一个全局Max来计算总的最大值。返回全局Max即可。

Time Complexity is O(n^2). Space is O(n). n是点的个数。 

Note: localMax要初始化成1, 最小值就是1, 而不能是0.

一条竖线上的点如[3,4], [3,5]他们的斜率是Infinity. HashMap 的 key 就是infinity.

AC Java:

 1 /**
 2  * Definition for a point.
 3  * class Point {
 4  *     int x;
 5  *     int y;
 6  *     Point() { x = 0; y = 0; }
 7  *     Point(int a, int b) { x = a; y = b; }
 8  * }
 9  */
10 public class Solution {
11     public int maxPoints(Point[] points) {
12         if(points == null || points.length == 0){
13             return 0;
14         }
15         int max = 1;
16         if(points.length == 1){
17             return max;
18         }
19         for(int i = 0; i<points.length; i++){
20             
21             HashMap<Float,Integer> hm = new HashMap<Float,Integer>();//key存斜率,value存该斜率上的点
22             int same = 0; //重合的点的个数
23             int localMax = 1;  //error
24             for(int j = 0; j<points.length; j++){
25                 if(i == j){
26                     continue;
27                 }else if(points[i].x == points[j].x && points[i].y == points[j].y){
28                     same++;
29                     continue;
30                 }
31                 float slope = (float)(points[j].y - points[i].y) / (points[j].x - points[i].x);
32                 if(!hm.containsKey(slope)){
33                     hm.put(slope,2);
34                 }else{
35                     hm.put(slope,hm.get(slope)+1);
36                 }
37             }
38             for(int count : hm.values()){
39                 localMax = Math.max(localMax,count);
40             }
41             localMax +=same;
42             max = Math.max(max,localMax);
43         }
44         return max;
45     }
46 }

 Reference: http://www.cnblogs.com/springfor/p/3896120.html

你可能感兴趣的:(LeetCode Max Points on a Line)