作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/


题目地址: https://leetcode.com/problems/find-k-closest-elements/description/

题目描述:

Given a sorted array, two integers k and x, find the k closest elements to x in the array. The result should also be sorted in ascending order. If there is a tie, the smaller elements are always preferred.

Example 1:

Input: [1,2,3,4,5], k=4, x=3
Output: [1,2,3,4]

Example 2:
Input: [1,2,3,4,5], k=4, x=-1
Output: [1,2,3,4]

Note:

  1. The value k is positive and will always be smaller than the length of the sorted array.
  2. Length of the given array is positive and will not exceed 104
  3. Absolute value of elements in the array and x will not exceed 104

UPDATE (2017/9/19):

The arr parameter had been changed to an array of integers (instead of a list of integers). Please reload the code definition to get the latest changes.

题目大意

在数组arr中找出离x最近的k个数。

解题方法

方法一:堆

解法比较多。比较容易想到的一种解法是使用计算每个数字和x的距离,然后找出最近距离的数字。这就是常见的TopK问题。使用小根堆很容易实现。

时间复杂度是O(N),空间复杂度是O(N)。

class Solution(object):
def findClosestElements(self, arr, k, x):
"""
:type arr: List[int]
:type k: int
:type x: int
:rtype: List[int]
"""
N = len(arr)
sub = [((arr[i] - x) ** 2, i) for i in range(N)]
heapq.heapify(sub)
return sorted([arr[heapq.heappop(sub)[1]] for i in range(k)])

方法二:双指针

由于数组已经排序,完全可以从左右两个方向向中间遍历,每次找到距离大的那个数字,弹出去就好了,最后保留k个数字。

class Solution(object):
def findClosestElements(self, arr, k, x):
"""
:type arr: List[int]
:type k: int
:type x: int
:rtype: List[int]
"""
while len(arr) > k:
if x - arr[0] <= arr[-1] - x:
arr.pop()
else:
arr.pop(0)
return arr

方法三:二分查找

最简单思想的二分是找出x的位置,然后找出其旁边的k个数。但是下面这个做法惊为天人,比较区间两端的数值和x的距离,如果左边离得远了,就向右边走;如果右边离得远了,就像左边走。这个对二分查找的理解必须很深刻了。

class Solution(object):
def findClosestElements(self, arr, k, x):
"""
:type arr: List[int]
:type k: int
:type x: int
:rtype: List[int]
"""
left = 0
right = len(arr) - k
while left < right:
mid = left + (right - left) / 2
if x - arr[mid] > arr[mid + k] - x:
left = mid + 1
else:
right = mid
return arr[left : left + k]

参考资料:

http://www.cnblogs.com/grandyang/p/7519466.html

日期

2018 年 10 月 8 日 —— 终于开学了。

【LeetCode】658. Find K Closest Elements 解题报告(Python)的更多相关文章

  1. [LeetCode] 658. Find K Closest Elements 寻找K个最近元素

    Given a sorted array, two integers k and x, find the k closest elements to x in the array. The resul ...

  2. [leetcode]658. Find K Closest Elements绝对距离最近的K个元素

    Given a sorted array, two integers k and x, find the k closest elements to x in the array. The resul ...

  3. 658. Find K Closest Elements

    Given a sorted array, two integers k and x, find the k closest elements to x in the array. The resul ...

  4. 【LeetCode】347. Top K Frequent Elements 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 解题方法 解题方法 字典 优先级队列 日期 题目地址:https://l ...

  5. [LeetCode] 347. Top K Frequent Elements 解题思路 - Java

    Given a non-empty array of integers, return the k most frequent elements. For example,Given [1,1,1,2 ...

  6. 【LeetCode】206. Reverse Linked List 解题报告(Python&C++&java)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 迭代 递归 日期 [LeetCode] 题目地址:h ...

  7. 【LeetCode】654. Maximum Binary Tree 解题报告 (Python&C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 递归 日期 题目地址:https://leetcode ...

  8. 【LeetCode】784. Letter Case Permutation 解题报告 (Python&C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 回溯法 循环 日期 题目地址:https://leet ...

  9. [LeetCode] Find K Closest Elements 寻找K个最近元素

    Given a sorted array, two integers k and x, find the k closest elements to x in the array. The resul ...

随机推荐

  1. android listview展示图片

    最近学习android开发,感触颇多,和网站开发对比,还是有很大的差距,在这里记录一下. android listview展示图片 在网站开发上,展示图片非常简单,一个HTML img标签就搞定,加上 ...

  2. 自定义char类型字符,django中事务

    自定义char类型字符 # 自定义char类型,继承Field父类 class MyCharField(Field): def __init__(self, max_length, *args, ** ...

  3. Redis源码解析(1)

    在文章的开头我们把所有服务端文件列出来,并且标示出其作用: adlist.c //双向链表 ae.c //事件驱动 ae_epoll.c //epoll接口, linux用 ae_kqueue.c / ...

  4. 非线性回归支持向量机——MATLAB源码

    支持向量机和神经网络都可以用来做非线性回归拟合,但它们的原理是不相同的,支持向量机基于结构风险最小化理论,普遍认为其泛化能力要比神经网络的强.大量仿真证实,支持向量机的泛化能力强于神经网络,而且能避免 ...

  5. URLDNS分析

    学习了很久的Java基础,也看了很多的Java反序列化分析,现在也来分析学习哈最基础的URLDNS反序列化吧. Java反序列化基础 为了方便数据的存储,于是乎有了现在的Java序列化于反序列化.序列 ...

  6. 简述安霸pipeline及其关键参数--raw域模块

    何为pipeline: sensor输出是一种叫Bayer 格式的RAW数据图像.ISP 对RAW数据图像的处理流程就是我们说的ISP PipeLine.通过PipeLine的处理,我们可以从一副RA ...

  7. 学习java 7.3

    学习内容:定义类不需要加static 成员方法在多个对象时是可以共用的,而成员变量不可以共用,多个对象指向一个内存时,改变变量的值,对象所在的类中的变量都会改变 成员变量前加private,成员方法前 ...

  8. day15 内置函数和模块

    day15 内置函数和模块 1.三元表达式 代码如下: x = 1 y = 2 res = 'ok' if x > y else 'no' print(res) 输出结果:no 2.内置函数:重 ...

  9. 百度 IP 查询

    查询 IP 地址以及百度爬虫 IP 我们如果要查询 IP 地址,互联网上有很多提供IP查询服务的网站,我这里总结和归纳如下: 国内提供 IP 查询的网站: IP138 IPIP,提供 IP 详细信息, ...

  10. 最长公共子序列问题(LCS) 洛谷 P1439

    题目:P1439 [模板]最长公共子序列 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn) 关于LCS问题,可以通过离散化转换为LIS问题,于是就可以使用STL二分的方法O(nlogn ...