首页 \ 问答 \ 给定2D平面上的n个点,找到位于同一直线上的最大点数(Given n points on a 2D plane, find the maximum number of points that lie on the same straight line)

给定2D平面上的n个点,找到位于同一直线上的最大点数(Given n points on a 2D plane, find the maximum number of points that lie on the same straight line)

以下是我试图实施的解决方案

/**
 * Definition for a point.
 * class Point {
 *     int x;
 *     int y;
 *     Point() { x = 0; y = 0; }
 *     Point(int a, int b) { x = a; y = b; }
 * }
 */
 public class Solution {
    public int maxPoints(Point[] points) {
    int max=0;
    if(points.length==1)
        return 1;
     for(int i=0;i<points.length;i++){
         for(int j=0;j<points.length;j++){
         if((points[i].x!=points[j].x)||(points[i].y!=points[j].y)){
         int coll=get_collinear(points[i].x,points[i].y,points[j].x,points[j].y,points);
                  if(coll>max)
                    max=coll;
                }
                else{

                    **Case where I am suffering**

                }
           }
        }
  return max;
}
public int get_collinear(int x1,int y1,int x2, int y2,Point[] points)
{
    int c=0;
    for(int i=0;i<points.length;i++){
        int k1=x1-points[i].x;
        int l1=y1-points[i].y;
        int k2=x2-points[i].x;
        int l2=y2-points[i].y;
        if((k1*l2-k2*l1)==0)
            c++;
    }
    return c;
}
}

它运行在O(n ^ 3)。 我基本上做的是运行两个循环比较2d平面中的各个点。 然后取2点我将这2个点发送到get_collinear方法,该方法击中由这两个点形成的线与阵列的所有元素,以检查3个点是否共线。 我知道这是一种蛮力方法。 但是,如果输入是[(0,0),(0,0)],我的结果将失败。 else循环是我必须添加条件以找出这种情况的地方。 有人可以帮我解决这个问题。 在更好的运行时间是否存在更好的解决方案来解决这个问题。 我什么都想不到。


Below is the solution I am trying to implement

/**
 * Definition for a point.
 * class Point {
 *     int x;
 *     int y;
 *     Point() { x = 0; y = 0; }
 *     Point(int a, int b) { x = a; y = b; }
 * }
 */
 public class Solution {
    public int maxPoints(Point[] points) {
    int max=0;
    if(points.length==1)
        return 1;
     for(int i=0;i<points.length;i++){
         for(int j=0;j<points.length;j++){
         if((points[i].x!=points[j].x)||(points[i].y!=points[j].y)){
         int coll=get_collinear(points[i].x,points[i].y,points[j].x,points[j].y,points);
                  if(coll>max)
                    max=coll;
                }
                else{

                    **Case where I am suffering**

                }
           }
        }
  return max;
}
public int get_collinear(int x1,int y1,int x2, int y2,Point[] points)
{
    int c=0;
    for(int i=0;i<points.length;i++){
        int k1=x1-points[i].x;
        int l1=y1-points[i].y;
        int k2=x2-points[i].x;
        int l2=y2-points[i].y;
        if((k1*l2-k2*l1)==0)
            c++;
    }
    return c;
}
}

It runs at O(n^3). What I am basically doing is running two loops comparing various points in the 2d plane. And then taking 2 points I send these 2 points to the get_collinear method which hits the line formed by these 2 points with all the elements of the array to check if the 3 points are collinear. I know this is a brute force method. However in case where the input is[(0,0),(0,0)] my result fails. The else loop is where I have to add a condition to figure out such cases. Can someone help me with the solution to that. And does there exist a better solution to this problem at better run time. I can't think of any.


原文:https://stackoverflow.com/questions/20779024
更新时间:2023-04-14 14:04

最满意答案

除非您正在制作StreamReader派生类,否则我没有看到任何模拟StreamReader的要点。 如果您需要通过StreamReader提供测试输入,只需从任何合适的来源读取一些预定义的数据即可。


I don't see any points to mock StreamReader unless you're making StreamReader derived class. If you need to provide test input via StreamReader, just read some predefined data from any suitable source.

相关问答

更多
  • 您应该在自定义对象列表中转换responseData ,以便将其绑定到转发器 IList contacts = ParseResponse(responseData); ReportRepeater.DataSource = contacts; ReportRepeater.DataBind(); ParseResponse是一个这样的自定义方法: IList ParseResponse(string response) { var rtn = new List ...
  • 最简单的事情是Dispose (你真的应该这样做,它会关闭流),并在关闭它时将其设置为null 。 或者,您可以检查EndOfStream ,但这需要您阅读到流的末尾。 The easiest thing is to Dispose (you really should do that, it closes the stream too) it and set it to null when you close it. Optionally you could check for EndOfStream, ...
  • 没有 - 在这种情况下,调用者进行处理是传统的。 Nope - in this case it's traditional for the caller to do the disposing.
  • 要解析到特定的对象,您必须设置您想要的对象,请尝试下一步: var myUser = JsonConvert.DeserializeObject(responseFromServer); 编辑,如果包含多个 var myUserList = JsonConvert.DeserializeObject>(responseFromServer); to parse to an specific object you hav ...
  • 当你读到reader2的结尾时,你真的正在读取底层流( responseStream2 )的末尾。 此时从该流中读取的另一个将失败。 虽然稍微有些特殊的例外情况,但是将不同的StreamReaders包装成同样的流将会造成奇怪的事情,因为这是一件奇怪的事情。 如果你需要读两次流,你需要使用支持重置位置的流(即随机访问),然后为第二次读取创建一个新的读取器; 或者(在这种情况下看起来很可能:我怀疑任何网络流将支持随机访问)自己缓冲流内容。 When you read to the end of reader2 ...
  • 目前尚不清楚为什么要在这里使用模拟。 是的,使用TextReader而不是要求StreamReader会给你更多的灵活性。 极少数情况下,它明确指定StreamReader作为参数或返回类型。 如果要为StreamReader提供测试数据,只需创建一个包装MemoryStream的StreamReader 当你返回一个StringReader ,它确实会在它被强制转换时(或者在模拟框架本身中)引起异常。 不幸的是,您的异常处理过于宽泛,因此很难看到该问题。 你的catch块应该只能捕获IOException ...
  • 作为问题解决方案的一部分,我需要进行不同的调用来实现它,而不是通过调用单个时间来循环它。 As a part of solution of the problem, I need to make different calls to achieve it instead of looping it by calling single time.
  • 没有必要Peek() ,这实际上也可能是问题。 你可以这样做: string line = reader.ReadLine(); while (line != null) { if (!String.IsNullOrEmpty(line) && !line.StartsWith("//")) { count++; } line = reader.ReadLine(); } 当然,如果您的StreamReader为null,则表示您遇到问题,但仅凭示例代码还不 ...
  • 为什么不尝试通过FileStream作为字节数组读取文件? byte[] fileContents = File.ReadAllBytes( @"c:\foo\bar\bazbat.txt" ) ; 这必须是某种编码问题(例如,您尝试将其作为UTF-8编码文本读取,并且该文件实际上是使用其他编码进行编码的。)。 Why don't you try reading the file via a FileStream as an array of bytes? byte[] fileContents = Fi ...
  • 除非您正在制作StreamReader派生类,否则我没有看到任何模拟StreamReader的要点。 如果您需要通过StreamReader提供测试输入,只需从任何合适的来源读取一些预定义的数据即可。 I don't see any points to mock StreamReader unless you're making StreamReader derived class. If you need to provide test input via StreamReader, just read ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)