有人能从oo设计和编码风格的角度对以下代码提供一些反馈吗?
问题:给定二维平面上的n个点,找出它上有最大点数的直线。类似于https://leetcode.com/problems/max-points-on-a-line/description/。给我提供了Point接口、空行类、空解决方案类,并要求我填写一些函数。
我的密码:
public interface Point
{
public double getX();
public double getY();
}
public class Line
{ // added by myself.
private Point p1, p2;
public Line(Point p1, Point p2) {
this.p1 = p1;
this.p2 = p2;
}
}
public class Solution
{
// Write the function here
public Line maxPointsLine(Point[] points) {
if(points == null) return null;
if(points.length==1) return new Line(points[0], new Point(p));//
Map<Double, Integer> map = new HashMap<>();// O(n), n = points.length. n-1
Line result;
int maxPoints = 0;
for(int i = 0; i < points.length; i++) { // One Point
map.clear();
int overlap =0;
int countSameX = 1;
for(int j = i+1; j < points.length; j++) { // the second Point
double x = points[j].getX() - points[i].getX(); // x intersect
double y = points[j].getY() - points[i].getY(); // intersect on y coordinate
if(x==0 && y==0) {
overlap++;
}
if(points[j].getX()==points[i].getX()) {// slope is infi,
// slope (1) finite, (2) infinite,
countSameX++;
continue;
}
double slope = y/x;
if(map.contains(slope)) map.put(slope, map.get(slope)+1);
else map.put(slope, 2);
if(map.get(slope)+overlap > maxPoints) { // each line slope and points[i]
// update result and maxPoints
maxPoints = map.get(slope)+overlap;
result = new Line(points[i], points[j]);
}
}
if(countSameX>maxPoints) { // line parallel to Y coordinate
// update result and maxPoints
maxPoints = countSameX;
result = new Line(points[i], points[j]);
}
}
return result;// null
}
}在上述代码中,我根据被问到的问题添加了一些评论。
)我很久以前就做过这个编码问题。我脑子里突然浮现出来。)事实上,面试官告诉我didn’t have good coding style and lack of OO design。欢迎对我的建议,以提高我自己。谢谢。
顺便说一句,关于编码风格,有一些插件遵循像https://google.github.io/styleguide/javaguide.html这样的标准。由于时间不够,我只是没有手动修复编码风格的问题。
至于OO设计,我得到的是空的课程。我只是添加了一些函数来解决我被赋予的问题。
我真的没发现我的密码里有什么大问题。困惑和沮丧。
发布于 2018-03-06 10:42:22
我认为您的任务是使用给定的类Point和Line并扩展它们.
public class Line{
public Line (Point a, Point b);
public boolean contains(Point p);
}因此,在解决方案中留下一个相当简单的任务(并且非常容易阅读)
Lines lines = getAllLines();//easily iterate over the permutated Point matrix
for(Line line: lines){
int amountOfPoints = 0;
for (Point p: points){
if (line.contains(p) {
amountOfPoint = amountOfPoint + 1;
}
}这只是对面向对象编程的一种解释,我没有包括子项,例如如何获得行的最大值,或者contains()是如何工作的,但它确实给出了问题的目标所在。
https://codereview.stackexchange.com/questions/188899
复制相似问题