LeetCode - Find K Closest Elements
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的更多相关文章
- [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 ...
- [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 ...
- 【LeetCode】658. Find K Closest Elements 解题报告(Python)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址: https://leetcode.com/problems/find-k-c ...
- [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 ...
- [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 ...
- 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 ...
- [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 ...
- 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 ...
- [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 ...
随机推荐
- js中字符串转数字的方法
1.当字符串中是纯数字 例如:var s = '234'; /********** 字符串在运算操作中会被当做数字类型来处理 ***************/ s *= 1; /******* str ...
- vue-router-7-重定向及别名
const router = new VueRouter({ mode: 'history', base: __dirname, routes: [ { path: '/', component: H ...
- mysql中sql查询使用注意
1.注意DESC关键字仅适用于在它前面的列名(birth):不影响species列的排序顺序. SELECT name, species, birth FROM pet ORDER BY specie ...
- VCL界面控件DevExpress VCL Controls发布v18.2.3|附下载
DevExpress VCL Controls是 Devexpress公司旗下最老牌的用户界面套包.所包含的控件有:数据录入,图表,数据分析,导航,布局,网格,日程管理,样式,打印和工作流等,让您快速 ...
- DevExpress WPF v18.2新版亮点(五)
买 DevExpress Universal Subscription 免费赠 万元汉化资源包1套! 限量15套!先到先得,送完即止!立即抢购>> 行业领先的.NET界面控件2018年第 ...
- SharePoint REST API - 列表和列表项
博客地址:http://blog.csdn.net/FoxDave 本篇主要讲述如何用SharePoint REST操作列表和列表项.阅读本篇时请先了解前面讲述的REST介绍和基本操作. 废话不多 ...
- python23的区别-日常记录
1. xrange:python3 中取消了range函数,把python2中的xrange重新命名为range,所以在python3中直接用range就行. 2. print:python3中pri ...
- webview定位 & native和webview切换
前言:现在的app大都是混合式的native+webview,对于native可以直接用uiautomator定位然后操作元素,但是web就定位不到了 一.先看看使用native定位的 二.定位web ...
- leetcode第40题:组合总和II
给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合. candidates 中的每个数字在每个组合中只能使用一次. ...
- winform 与百度搜索智能提示
private void textBox1_TextChanged(object sender, EventArgs e) { listBox1.Items.Clear(); if (string.I ...