Lintcode 612. K个最近的点
来源:互联网 发布:身份证复制软件3.7 编辑:程序博客网 时间:2024/05/18 01:20
给定一些 points
和一个origin
,从 points
中找到 k
个离 origin
最近的点。按照距离由小到大返回。如果两个点有相同距离,则按照x值来排序;若x值也相同,就再按照y值排序。
方法一(硬写):
"""Definition for a point.class Point: def __init__(self, a=0, b=0): self.x = a self.y = b"""class Solution: """ @param: points: a list of points @param: origin: a point @param: k: An integer @return: the k closest points """ def kClosest(self, points, origin, k): # write your code here for i in range(len(points)): for j in range(i+1, len(points)): distance_1 = (pow(points[i].x-origin.x, 2) + pow(points[i].y-origin.y, 2)) distance_2 = (pow(points[j].x-origin.x, 2) + pow(points[j].y-origin.y, 2)) if distance_1 > distance_2: points[i], points[j] = points[j], points[i] elif distance_1 == distance_2: if(points[i].x > points[j].x or (points[i].x == points[j].x and points[i].y > points[j].y)): points[i], points[j] = points[j], points[i] return points[0:k]
方法二(利用python自带的排序方法)
"""Definition for a point.class Point: def __init__(self, a=0, b=0): self.x = a self.y = b"""class Solution: """ @param: points: a list of points @param: origin: a point @param: k: An integer @return: the k closest points """ def kClosest(self, points, origin, k): # write your code here points.sort(key=lambda t: ((t.x-origin.x)**2+(t.y-origin.y)**2, t.x, t.y)) return points[0:k]
阅读全文
0 0
- 612. K个最近的点[LintCode]
- Lintcode 612. K个最近的点
- lintcode[612]:k个最近的点
- Lintcode-K个最近的点(#612)
- LintCode:M-K个最近的点
- LintCode K个最近的点
- LintCode: K个最近的点
- K个最近的点-LintCode
- LintCode-[中等] 612. K个最近的点
- K个最近的点
- K个最近的点
- k个最近的点(Leetcode答案)
- 计算二维空间某点的最近k 个点
- 【K-D树 K维最近距离的t个点】HDU
- 在一个二维平面上找到离固定点最近的k个点位置
- m维空间里n个点每点最近的第k个点的距离
- 算法爱好者——K个最近的点 ? 待解决
- LintCode-第k个排列
- [6]_编译内核错误提示1:Unable to find the ncurses libraries or the 和 E: Unable to locate package ncurse
- 读书笔记《C++ Primer》第五版——第十二章 动态内存
- 实用idea代码编辑快捷键
- Spring boot下 拦截器中的Service空指针异常解决方法
- 数据结构之排序二叉树递归建立,递归查找
- Lintcode 612. K个最近的点
- 装饰模式
- 第十三周java作业--集合框架
- Mysql基本命令之事务处理
- sql的基本语句
- Java拾遗系列- io知识
- Linux基础:日志管理
- DNS错误不能上网怎么办 电脑dns错误修复方法
- ZC702开发板-上电测试