Leetcode: max-points-on-a-line
来源:互联网 发布:淘宝学生家代购 编辑:程序博客网 时间:2024/06/06 03:02
题目:
Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.
分析:
题目是给定一个二维平面上的点,希望求得这个平面上经过最多点的直线经过了多少个点。解这个题目需要用到穷举的思想,即计算每个点到其他点的斜
率,如果斜率相同,则共线。按照这个思路我们可以创建一个键为double,值为int类型的HashMap,穷举每两个点之间的斜率时,判断HashMap中是否
存在该斜率,没有就创建这个斜率的键值对,有就将值加1。需要考虑与该点重合还有垂直的情况。
具体代码如下:
/** * Definition for a point. * class Point { * int x; * int y; * Point() { x = 0; y = 0; } * Point(int a, int b) { x = a; y = b; } * } */import java.util.HashMap;public class Solution { public int maxPoints(Point[] points) { int len = points.length; if (len < 2) return len; int ret = 0; for (int i = 0; i < len; i++){ int chuizhi = 0; int chonghe = 1; HashMap<Double, Integer> hm = new HashMap<Double, Integer>(); for (int j = 0; j < len; j++){ if (i == j) continue; else{ int diffX = points[i].x - points[j].x; int diffY = points[i].y - points[j].y; if (diffX == 0 && diffY == 0){ chonghe++; } else if (diffX == 0){ chuizhi++; } else{ double slope = diffY*1.0/diffX; if (hm.get(slope) == null){ hm.put(slope, 1); } else{ hm.put(slope, hm.get(slope)+1); } } } } int max = chuizhi; for(double k : hm.keySet()){ max = Math.max(max, hm.get(k)); } ret = Math.max(ret, max+chonghe); } return ret; } }
阅读全文
1 0
- Max Points on a Line | leetcode
- Max Points on a Line LEETCODE
- Leetcode: Max Points on a Line
- LeetCode - Max Points on a Line
- LeetCode 之 Max Points on a Line
- LeetCode | Max Points on a Line
- [LeetCode] Max Points on a Line
- Leetcode: Max Points on a Line
- LeetCode OJ:Max Points on a Line
- Leetcode Max Points on a Line
- Leetcode: Max Points on a Line .
- [Leetcode] Max Points on a Line (Java)
- leetcode:【Max Points on a Line】
- Max Points on a Line - LeetCode
- LeetCode:Max Points on a Line
- [LeetCode] Max Points on a Line
- leetcode - Max Points on a Line
- LeetCode(149)Max Points on a Line
- Java虚拟机(四)垃圾收集算法
- C++_008_数据结构_线性表_普通线性表
- 大数据架构和模式(二)如何知道一个大数据解决方案是否适合您的组织
- Codeforces Beta Round #2 A. Winner
- HDU:1757 A Simple Math Problem
- Leetcode: max-points-on-a-line
- 人事面试一百问
- Linux下启动、停止xampp命令
- CUDA学习教程
- 数据挖掘基础入门实验
- malloc calloc realloc free的简单实现
- 阶层位数
- 2017 WUST校赛 1009 LL&a+b-c
- 中缀表达式转换成后缀表达式并求值