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. 总结5条对学习Linux系统有帮助的经验心得

    作为国产手机中的代表厂商,OPPO一直走在国内的前沿.不仅手机出货量在国内遥遥领先,而且在国外也抢占不少的市场份额.前段时间,OPPO在台湾地区签下田馥甄和林宥嘉担任OPPO R9s的代言人外,在东南 ...

  2. git教程(全)

    参考: http://blog.jobbole.com/78960/

  3. 【原创】<Debug> “duplicate connection name”

    [Problem] duplicate connection name [Solution] 在Qt上使用SQLite的时候,如果第二次使用QSqlDatabase::addDatabase()方式时 ...

  4. sqlalchemy tree 树形分类 无限极分类的管理。预排序树,左右值树。sqlalchemy-mptt

    简介: 无限极分类是一种比较常见的数据格式,生成组织结构,生成商品分类信息,权限管理当中的细节权限设置,都离不开无限极分类的管理. 常见的有链表式,即有一个Pid指向上级的ID,以此来设置结构.写的时 ...

  5. vue-6-事件处理

    <div id="example-2"> <button v-on:click="greet">Greet</button> ...

  6. 八. Python基础(8)--函数

    八. Python基础(8)--函数 1 ● 函数返回布尔值 注意, 自定义的函数也可以是用来作逻辑判断的, 例如内置的startswith()等函数. def check_len(x):     ' ...

  7. Python的网络编程--思维导图

    Python的网络编程--思维导图

  8. sass 继承 占位符 %placeholder

    @extend //SCSS .btn { border: 1px solid #ccc; padding: 6px 10px; font-size: 14px; } .btn-primary { b ...

  9. loadrunner请求json数据参数化问题

    http://blog.sina.com.cn/s/blog_62079f620102vvx3.html

  10. 软件工程结对作业01 psp表格