Problem: Given a two-dimensional graph with points on it, find a line which passes the most number of points.

此题是Cracking the code 5th edition 第七章第六题,思路就是 n choose 2, 所以时间复杂度是O(n^2),因为没有更快的办法。

此题的难点在于两点一线计算出的斜率是浮点型,不好比较equality。所以其中需要有一个精确到哪一位的概念,英文是 round to a given place value.

我认为此题书中给的解法特别傻逼,而且时间复杂度也超出了O(n^2),故自己写了一个更好的版本。

另,关于使用自定义类用作HashMap的键值,如何重写equals()和hashCode(),下面的代码给出的很好的示范。

package chapter7;

import java.util.HashMap;

// given a two-dimensional graph with points on it,
// find a line which passes the most number of points
// Time: O(N^2), N is number of points // The tricky part is checking the equality of slope
// which is of type double.
// My solution is floor all values to an epsilon value
// which specifies the desired precision public class P6 { public Line findBestLine(GraphPoint[] points){
Line bestLine = null;
int bestCount = 0;
HashMap<Line, Integer> lineCounts =
new HashMap<Line, Integer>(); for(int i = 0; i < points.length; ++i){
for(int j = i+1; j < points.length; ++j){
Line line = new Line(points[i], points[j]);
int currentCount; if(lineCounts.containsKey(line)){
currentCount = lineCounts.get(line) + 1;
}else{
currentCount = 1;
}
lineCounts.put(line, currentCount); if(currentCount > bestCount){
bestCount = currentCount;
bestLine = line;
}
}
} return bestLine;
}
} class Line{
// for precision
// slope and intercept values are floored to epsilon
public static double epsilon = .0001; // properties for a normal line
public double slope;
public double y_intercept; // properties for a verticle line
public boolean infinite_slope = false;
public double x_intercept; public Line(GraphPoint p1, GraphPoint p2){ if(p1.x == p2.x){
this.infinite_slope = true;
this.x_intercept = p1.x; }else{
this.slope = (p1.y - p2.y) / (p1.x - p2.x);
this.y_intercept = p1.y - slope * p1.x; } // floor all properties
this.slope = floor(this.slope);
this.x_intercept = floor(this.x_intercept);
this.y_intercept = floor(this.y_intercept);
} public double floor(double val){
int val2 = (int)(val / epsilon);
return val2 * epsilon;
} @Override
public int hashCode(){
if(infinite_slope){
return (int) x_intercept;
}else{
return (int) (slope + y_intercept);
}
} @Override
public boolean equals(Object obj){
if(this == obj)
return true;
if(obj == null)
return false;
if(getClass() != obj.getClass())
return false; Line other = (Line)obj; if(infinite_slope && other.infinite_slope){ // both true
return x_intercept == other.x_intercept; }else if(infinite_slope || other.infinite_slope){ // one true, one false
return false;
}
else{ // both false
return slope == other.slope && y_intercept == other.y_intercept;
}
}
} class GraphPoint{
// assume that x and y are both floored
// to some point
public double x;
public double y;
}

  

[CC150] Find a line passing the most number of points的更多相关文章

  1. [CareerCup] 7.6 The Line Passes the Most Number of Points 经过最多点的直线

    7.6 Given a two-dimensional graph with points on it, find a line which passes the most number of poi ...

  2. [LeetCode OJ] Max Points on a Line—Given n points on a 2D plane, find the maximum number of points that lie on the same straight line.

    //定义二维平面上的点struct Point { int x; int y; Point(, ):x(a),y(b){} }; bool operator==(const Point& le ...

  3. Keys of HashMap in Java

    The tricky thing is how to decide the key for a hashmap. Especially when you intend to use self-defi ...

  4. CareerCup All in One 题目汇总 (未完待续...)

    Chapter 1. Arrays and Strings 1.1 Unique Characters of a String 1.2 Reverse String 1.3 Permutation S ...

  5. iOS: 如何正确的绘制1像素的线

    iOS 绘制1像素的线 一.Point Vs Pixel iOS中当我们使用Quartz,UIKit,CoreAnimation等框架时,所有的坐标系统采用Point来衡量.系统在实际渲染到设置时会帮 ...

  6. [ACM_几何] Transmitters (zoj 1041 ,可旋转半圆内的最多点)

    Description In a wireless network with multiple transmitters sending on the same frequencies, it is ...

  7. poj 1106 Transmitters (叉乘的应用)

    http://poj.org/problem?id=1106 Time Limit: 1000MS   Memory Limit: 10000K Total Submissions: 4488   A ...

  8. BZOJ3315: [Usaco2013 Nov]Pogo-Cow

    3315: [Usaco2013 Nov]Pogo-Cow Time Limit: 3 Sec  Memory Limit: 128 MBSubmit: 143  Solved: 79[Submit] ...

  9. poj1981 Circle and Points 单位圆覆盖问题

    转载请注明出处: http://www.cnblogs.com/fraud/          ——by fraud Circle and Points Time Limit: 5000MS   Me ...

随机推荐

  1. c语言,strcpy

    #include <stdio.h> #include <string.h> int main() {  char string[10];  char *str="a ...

  2. bootstrap整理-1

    基本的HTML模板 小伙伴们,上一小节的视频课程已经对Bootstrap提供的模板做了详细的介绍,在这一小节中我们把这个模板代码粘贴过来,以供你们学习查看,你们可以根据实际情况在此基础上进行扩展,只需 ...

  3. 无法打开登录所请求的数据库 "XXX"。登录失败。 用户 'NT AUTHORITY\SYSTEM' 登录失败。

    1.打开数据库安全性-登录名 2.选择NT AUTHORITY\SYSTEM右键属性 3.选择服务器角色勾选sysadmin选项保存

  4. Android Studio快捷键快速入门

    调整,Settings->IDE Settings->Editor->Appearance->Show line numbers  显示代码行数Settings->IDE ...

  5. Highcharts在IE中不能一次性正常显示的一种解决办法

    由于客户要求必须在IE浏览器下兼容图表,故选用了兼容性较好的Highcharts.另外说一句,博主尝试过ichartjs.ECharts.YUI,兼容性都没有Highcharts给力(所有的兼容性问题 ...

  6. Web前端/后端

       Web前端:         1)精通HTML,能够书写语义合理,结构清晰,易维护的HTML结构.         2)精通CSS,能够还原视觉设计,并兼容业界承认的主流浏览器.         ...

  7. CDN调度器HAProxy、Nginx、Varnish

    http://www.ttlsa.com/web/the-cdn-scheduler-nginx-haproxy-varnish/ CDN功能如下:1.将全网IP分为若干个IP段组,分组的依据通常是运 ...

  8. 广告系统中weak-and算法原理及编码验证

    wand(weak and)算法基本思路 一般搜索的query比较短,但如果query比较长,如是一段文本,需要搜索相似的文本,这时候一般就需要wand算法,该算法在广告系统中有比较成熟的应 该,主要 ...

  9. facebook登录(集成FBSDKLoginKit) result的isCancelled总是YES token为nil

    只需要在AppDelegate如下函数添加: - (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDict ...

  10. O-C相关-08-动态类型与静态类型

    08-动态类型与静态类型 1, 什么是动态类型和静态类型 1) 动态语言 又叫动态编程语言,是指程序在运行时可以改变其结构:新的函数可以被引进,已有的函数可以被删除等在结构上的变化.比如众所周知的EC ...