zoukankan      html  css  js  c++  java
  • K个最近的点

    前段时间在网上看到一些准备找工作的人会在LintCode上刷题,然后我今天上去看了一下,也打算开始做题,然后把每天做的题目和以后的优化记录下来。

    2017年8月6日 21:17:27

    第一题:

    描述:给定一些 points 和一个 origin,从 points 中找到 k 个离 origin 最近的点。按照距离由小到大返回。如果两个点有相同距离,则按照x值来排序;若x值也相同,就再按照y值排序。

    样例:给出 points = [[4,6],[4,7],[4,4],[2,5],[1,1]], origin = [0, 0], k = 返回 [[1,1],[2,5],[4,4]]


    下面是我的代码:

     1     class Point
     2     {
     3         public int x;
     4         public int y;
     5         public Point() { }
     6         public Point(int x,int y) { this.x = x;this.y = y; }
     7     }
     8     class Program
     9     {
    10         static void Main(string[] args)
    11         {
    12             Point[] ps=new Point[]{new Point(4,6),new Point(4,7),new Point(4,4) ,new Point(2,5),new Point(1,1)};
    13             Point[] pfinal = Closest(ps, new Point(0, 0), 3);
    14             foreach(Point p in pfinal)
    15             {
    16                 Console.WriteLine($"({p.x},{p.y})");
    17             }
    18             Console.ReadKey();
    19         }
    20         static Point[] Closest(Point[] points,Point origin, int k)
    21         {
    22             Point[] plist = new Point[k];
    23             List<int> list = new List<int>();
    24             for(int i =0;i<points.Length;i++)
    25             {
    26                 list.Add(GetLen(points[i], origin));
    27             }
    28             list.Sort();
    30             for (int i = 0; i <points.Length; i++)
    31             {
    32                 for(int j=0;j<k;j++)
    33                 {
    34                     if (list[j] == GetLen(points[i], origin))
    35                         plist[j] = points[i];
    36                 }
    37             }
    38             return plist;
    39         }
    40         static int GetLen(Point p1,Point p2)//获取两点间距离
    41         {
    42             return Convert.ToInt32(Math.Sqrt((p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y)));
    43         }
    44     }

    前一部分的思想是使用GetLen方法获取每个点到给定点的距离,然后把距离添加到一个List集合中,然后将List使用Sort排序,输出前K个点就可以了;

    但是后来发现我无法区分哪个距离是哪个点和给定点之间的距离,都想使用Dictionary了。。。

    然后问了一下室友,室友提供了一个方法:将距离保存到List集合后,再次遍历所有点,判断循环时当前点到给定点的距离和前k个距离相等时,获取当前点即可。

    虽然按照样例中的数据测试是对的,但是对于对称点我觉得会出现错误,所以明天有时间再更新一次!

  • 相关阅读:
    《软件测试经验与教训》—读书笔记
    【转】性能测试工程师的素质
    【转】如何成为优秀的性能测试工程师
    性能测试学习之路
    FTP 、TCP/IP、HTTP、Cookies、Session
    Loadrunner工具介绍
    tesseract-ocr图像识别技术(一)
    MongoDB 自动分片 auto sharding
    mongodb 3.0下载安装、配置及mongodb最新特性、基本命令教程详细介绍
    java使用memcached2--集群部署
  • 原文地址:https://www.cnblogs.com/yh2015/p/7296072.html
Copyright © 2011-2022 走看看