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. getopts的使用方法

    getopts的使用 语法格式:getopts [option[:]] [DESCPRITION] VARIABLE option:表示为某个脚本可以使用的选项 ":":如果某个选 ...

  2. linux生成SSH key

    1. 检查SSH keys是否存在 ls -al ~/.ssh2. 生成新的ssh key 输入 ssh-keygen -t rsa -C your_email@example.com

  3. angular4-表单

    导入表单模块 import { FormsModule } from '@angular/forms'; // ... @NgModule({ imports: [BrowserModule, For ...

  4. 前端之Bootstrap框架

    一.Bootstrap介绍 Bootstrap是Twitter开源的基于HTML.CSS.JavaScript的前端框架. 它是为实现快速开发Web应用程序而设计的一套前端工具包. 它支持响应式布局, ...

  5. (C/C++学习笔记) 二十二. 标准模板库

    二十二. 标准模板库 ● STL基本介绍 标准模板库(STL, standard template library): C++提供的大量的函数模板(通用算法)和类模板. ※ 为什么我们一般不需要自己写 ...

  6. aspnet core 2.0 发布之后没有 views文件夹

    在项目文件里面 增加这个节点: MvcRazorCompileOnPublish 设置为false 是会发布views <PropertyGroup> <PackageTargetF ...

  7. [rancher-net]

    ip rule命令 rancher网络全解读 arp命令查询 rancher managed network 实践 docker自定义网桥 iptables增删改查 shell脚本调试技术

  8. centos服务器删除/usr目录怎么办

    凉拌 两种方法: 第一:重装系统,因为你的大部分命令使用不了了,如果你的服务器还有应用程序在跑,那你的服务也会有问题,因为一些服务的lib包也会放在此目录下,貌似需要重新装才可以 第二:利用ios镜像 ...

  9. 配置MAVEN环境变量

    在配置maven前一定要先配置java jdk 的环境变量 和java配置一样 先写一个MAVEN_HOME:F:\java\apache-maven-3.5.2 (就是你maven 的下载位置) 写 ...

  10. HDU 1796 How many integers can you find(容斥原理)

    题目传送:http://acm.hdu.edu.cn/diy/contest_showproblem.php?cid=20918&pid=1002 Problem Description    ...