leetcode--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.

 

public class Solution {
	/**
	 * This program is used to calculate the number of points on a line on a plane.
	 * The algorithm is simple if there is no doubt on the definition of a line.
	 * A line can be defined using a single point and slope, one can obtain the analytic expression.
	 * So, the algorithm in the program is the following:
	 * 1. For a fixed point, calculate the maximum number of points on the same line with the 
	 * fixed point.
	 * 2. run a loop with respect to each point.
	 * 
	 * @param points -- an array of points on plane
	 * @return maximum number of points on a line
	 * @author Averill Zheng
	 * @version 2014-06-01
	 * @since JDK 1.7
	 */
	 public int maxPoints(Point[] points) {
		 int numberOfPoints = 0;
		 int length = points.length;
		 for(int i = 0; i < length; ++i){
			 int max = maxPointsForFixedInterception(i, points);
			 numberOfPoints = (numberOfPoints < max) ? max : numberOfPoints;
		 }
		 return numberOfPoints;
	 }
	 
	 private int maxPointsForFixedInterception(int i, Point[] points){
		 int max = 0, length = points.length;
		 Map<Double, Integer> slope = new HashMap<Double, Integer>();
		 
		 if(length > 0){
			 max = 1;
			 if(length > 1){				
				 //on vertical line
				 int number = 1;
				 for(int j = 0; j < length; ++j){
					 if(j != i){
						 double x_coor = points[j].x - points[i].x;
						 double y_coor = points[j].y - points[i].y;
						 //on vertical-line
						 if(x_coor == 0 && y_coor != 0){
							 ++number;
							 max = (max < number)? number : max;
						 }
						 //repeat points
						 else if(x_coor == 0 && y_coor == 0){
							 ++max;
						 }
						 else{
							 double slopeValue = y_coor / x_coor;
							 if(slope.containsKey(slopeValue)){
								 int num = slope.get(slopeValue) + 1;
								 max = (max < num) ? num : max;
								 slope.put(slopeValue, num);
							 }
							 else{
								 max = (max < 2) ? 2 : max;
								 slope.put(slopeValue, 2);
							 }
						 }
					 }
				 }
			 }
		 }
		 return max;
	 }
}    

  

转载于:https://www.cnblogs.com/averillzheng/p/3765082.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值