博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【leetcode】973. K Closest Points to Origin
阅读量:7179 次
发布时间:2019-06-29

本文共 1336 字,大约阅读时间需要 4 分钟。

题目如下:

We have a list of points on the plane.  Find the Kclosest points to the origin (0, 0).

(Here, the distance between two points on a plane is the Euclidean distance.)

You may return the answer in any order.  The answer is guaranteed to be unique (except for the order that it is in.)

 

Example 1:

Input: points = [[1,3],[-2,2]], K = 1Output: [[-2,2]]Explanation: The distance between (1, 3) and the origin is sqrt(10).The distance between (-2, 2) and the origin is sqrt(8).Since sqrt(8) < sqrt(10), (-2, 2) is closer to the origin.We only want the closest K = 1 points from the origin, so the answer is just [[-2,2]].

Example 2:

Input: points = [[3,3],[5,-1],[-2,4]], K = 2Output: [[3,3],[-2,4]](The answer [[-2,4],[3,3]] would also be accepted.)

 

Note:

  1. 1 <= K <= points.length <= 10000
  2. -10000 < points[i][0] < 10000
  3. -10000 < points[i][1] < 10000

解题思路:太简单了,没啥说的。

代码如下:

class Solution(object):    def kClosest(self, points, K):        """        :type points: List[List[int]]        :type K: int        :rtype: List[List[int]]        """        l = []        for x,y in points:            l.append((x,y,x*x+y*y))        def cmpf(v1,v2):            return v1[2] - v2[2]        l = sorted(l,cmp=cmpf)[:K]        res = []        for x,y,z in l:            res.append([x,y])        return res

 

转载于:https://www.cnblogs.com/seyjs/p/10295053.html

你可能感兴趣的文章
应对 win2003server 服务自动关闭的方案
查看>>
错误:Forefront TMG管理无法连接到配置存储服务器
查看>>
Java多线程——非原子64位操作(long,double)
查看>>
Maver使用外部的jar 包问题
查看>>
mySQL event
查看>>
jQuery子窗体如何取得父窗体的元素
查看>>
Office365 Exchange Hybrid No.06 ADFS场高可用部署
查看>>
Office365 Exchange Hybrid No.01 基础介绍
查看>>
Dsadd命令参数
查看>>
批量修改域客户端administrator密码以及更新密码框为灰色处理办法!
查看>>
Exchange 2010 批量删除特定关键字邮件
查看>>
使用MDT2012部署Windows&Linux操作系统(5)
查看>>
DNS
查看>>
我的友情链接
查看>>
grails 列出i18n内容
查看>>
学习 Dialplan 5.宏指令
查看>>
二叉树(层次遍历)非递归
查看>>
Go 生成图片
查看>>
命令-df/du
查看>>
整合 Tachyon 运行 Apache Flink(译)
查看>>