LeetCode-03 穷举

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

给定二维平面上n个点,找出位于同一直线上的点的最大数目。

思路:
位于同一直线:斜率((y2-y1) / (x2-x1))相同。
1、用双重循环即可解决问题,外层循环依次以每个点作为基准,内层循环中用其余各点与固定点计算斜率,垂直和重合情况分别考虑。
2、对于外层循环中每个点,定义一个map,key:斜率(Double) value:相同斜率出现的次数(Integer)。
3、内层循环走完一轮回,从map中得出与固定点在同一直线上点的最大数量,即为max。
4、内层循环走完一轮回,更新max的值。
5、最后max为所求。
边界条件:
只给出0个点或者一个点:结果位于同一直线上点的最大数量为0或1;
垂直 (x2 = x1) :斜率不存在;
重合 (y2 = y1, x2=x1) :给出的n个点坐标,可能有坐标相同的点,导致重合的情况;
其他正常情况。

Java代码:

import java.util.HashMap;
import java.util.Map;

class Point {
    int x;
    int y;
    public Point() {
        this.x = 0;
        this.y = 0;
    }
    public Point (int x, int y) {
        this.x = x;
        this.y = y;
    }
}
public class Solution {
    public static int maxPoints(Point[] points) {
        int len = points.length;
        if(len < 2) {
            return len;//考虑到只有0/1个点的情况
        }       
        int max = 0;

        for(int i = 0; i < len ; i ++) {
            Map<Double,Integer> map = new HashMap<Double,Integer>();
            int cz = 0;//x1 = x2,垂直即斜率不存在的情况
            int ch = 0;// 给出的n个点可能有重合的点

            for(int j = 0; j < len ; j ++) {
                if(i == j) continue;
                if(points[i].x == points[j].x) {
                    if(points[i].y == points[j].y) {
                        ch ++;
                    }else {
                        cz ++;
                    }
                }
                else {
                    double key = 1.0 * (points[i].y - points[j].y)/(points[i].x - points[j].x);
                    map.put(key, map.get(key) == null ? 1 : map.get(key) + 1);
//                  if(!map.containsKey(key))
//                  {
//                      map.put(key, 1);
//                  }
//                  else {
//                      map.put(key, map.get(key)+1);
//                  } //此if-else用上面的一条语句即可解决
                }
            }
            int temp = cz;
            for(double k : map.keySet()) {
                temp = temp > map.get(k)? temp : map.get(k);
            }
            max = max > temp + ch + 1 ? max : temp + ch + 1;            
        }
        return max;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值