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:
The value k is positive and will always be smaller than the length of the sorted array.
Length of the given array is positive and will not exceed 104
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.

中了 priorityqueue 的毒,自己写了个比较繁琐的方法:

class Solution {
public List<Integer> findClosestElements(int[] arr, int k, int x) {
if(arr == null || arr.length == 0){
return new ArrayList<Integer>();
}
PriorityQueue<int[]> pq = new PriorityQueue<>((e1,e2) -> elementCompare(e1,e2));
for(int a : arr){
pq.add(new int[]{a,Math.abs(a-x)});
if(pq.size() > k){
pq.poll();
}
}
List<Integer> list = new ArrayList<>();
while(!pq.isEmpty()){
list.add(pq.poll()[0]);
}
Collections.sort(list);
return list;
}
private int elementCompare(int[] e1, int[]e2){
if(e1[1] != e2[1]){
return e2[1] - e1[1];
}
else{
return e2[0] - e1[0];
}
}
}

更合适的方法:

用binary search + 双指针来做, 注意最后加入list中的顺序问题:

class Solution {
public List<Integer> findClosestElements(int[] arr, int k, int x) {
if(arr == null || arr.length == 0){
return new ArrayList<Integer>();
}
List<Integer> list = new ArrayList<>();
int len = arr.length;
if(x >= arr[len-1]){
for(int i = len - k; i<len; i++){
list.add(arr[i]);
}
}
else if(x <= arr[0]){
for(int i = 0; i<k; i++){
list.add(arr[i]);
}
}
else{
int n = 0;
int l = 0;
int h = len - 1;
while(l <= h){
int mid = l + (h-l)/2;
if(arr[mid] == x || (arr[mid] > x && arr[mid-1] < x)){
n = mid;
break;
}
else if(arr[mid] > x){ h = mid - 1;
}
else if(arr[mid] < x){
l = mid + 1;
} }
int less = n-1, more = n;
while(less >= 0 && more < len && k > 0){
if(Math.abs(arr[less] - x) <= Math.abs(arr[more] - x)){
list.add(0, arr[less]);
less -- ;
}
else{
list.add(arr[more]);
more ++;
}
k--;
}
while(less >= 0 && k > 0){
list.add(0, arr[less--]);
k--;
}
while(more < len && k > 0 ){
list.add(arr[more++]);
k--;
}
}
return list;
} }

LeetCode - Find K Closest Elements的更多相关文章

  1. [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 ...

  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. 【LeetCode】658. Find K Closest Elements 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址: https://leetcode.com/problems/find-k-c ...

  4. [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 ...

  5. [Swift]LeetCode658. 找到 K 个最接近的元素 | Find K Closest Elements

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

  6. 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 ...

  7. [leetcode-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 ...

  8. 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 ...

  9. [LeetCode] Top K Frequent Elements 前K个高频元素

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

随机推荐

  1. servlet之中文乱码:request.getParameter()

    参考: http://blog.csdn.net/u014558484/article/details/53445178

  2. IDE 版本

    BDS 5 2007 D11  VER180 and VER185 RAD Studio 8 XE D15  VER 220 RAD 18 XE 10.1 Berlin D24  VER310  St ...

  3. Linux查看当前使用的网卡 以及 查看某进程使用的网络带宽情况 以及 端口占用的情况

    一:Linux查看当前使用的网卡          ifconfig命令可以查看当前linux 系统有多少个网卡. [app@p2-app2 ~]$ ifconfig br-2e5b046a02d5: ...

  4. ajax返回数据定义为全局变量

    var result;   //定义全局变量    $(document).ready(function(){          $.ajax({                   type:'PO ...

  5. dubbo-admin 无法支持JDK1.8

    dubbo-admin 无法支持JDK1.8怎么处理? 1.从git上下载最新源码 https://github.com/alibaba/dubbo 2.编译war包,或直接容器启动

  6. SharePoint REST API - REST请求导航的数据结构

    博客地址:http://blog.csdn.net/FoxDave 从一个既定的URL获取其他SharePoint资源 当你用SharePoint REST服务进行开发的时候,你经常会从指定的一个 ...

  7. WebService的一种简单应用方式入门

    1.什么是WebService? WebService即Web服务,简单来讲,他就是一种跨编程语言和跨操作平台的远程调用技术. 2.Web服务: Web服务是基于HTTP和XML的技术:HTTP是互联 ...

  8. 2019-03-01-day002-基础编码

    01 昨日内容回顾 编译型: 一次性编译成二进制. 优点:质型速度快. 确定:开发效率低,不能跨平台. 解释型: 逐行解释,逐行运行. 优点:开发效率高,可以跨平台. 缺点:回字形效率低. pytho ...

  9. scrapy shell的作用

    1.可以方便我们做一些数据提取的测试代码: 2.如果想要执行scrapy命令,那么毫无疑问,肯定是要先进入到scrapy所在的环境中: 3.如果想要读取某个项目的配置信息,那么应该先进入到这个项目中. ...

  10. 微软Power BI 每月功能更新系列——7月Power BI 新功能学习

    Power BI Desktop 7月产品功能摘要 7月是Power BI Desktop团队的重要发布!但由于官方延迟更新,我们的讲述也就更晚了一点,也许大家觉得没有必要了,都8月了,谁还看7月的? ...