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 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.
Approach #1:
class Solution {
public:
vector<int> findClosestElements(vector<int>& arr, int k, int x) {
int len = arr.size();
//cout << x << " " << k << endl;
if (x <= arr[0]) return vector<int> (arr.begin(), arr.begin()+k);
else if (x >= arr[len-1]) return vector<int> (arr.end()-k, arr.end());
else {
int index = lower_bound(arr.begin(), arr.end(), x) - arr.begin();
int low = max(0, index - k - 1), high = min(len-1, index+k-1);
while (high - low > k - 1) {
if (low < 0 || (x - arr[low]) <= (arr[high] - x)) high--;
else if (high > len-1 || (x - arr[low]) > (arr[high] - x)) low++;
}
return vector<int> (arr.begin()+low, arr.begin()+high+1);
}
}
};
Runtime: 72 ms, faster than 98.40% of C++ online submissions for Find K Closest Elements.
Analysis:
The original array has been sorted so we can take this advantage by the following steps.
- If the target
xis less or equal than the first element in the sorted array, the firstkelements are the result. - Similarly, if the target
xis more or equal than the last element in the sorted array, the lastkelements are the result. - Otherwise, we can use binary search to find the
indexof the element, which is equal (when this list hasx) or a little bit larger thanx(when this list does not have it). Then setlowto its leftk-1position, andhighto the rightk-1position of thisindexas a start. The desired k numbers must in this rang [index-k-1, index+k-1]. So we can shrink this range to get the result using the following rules.- If
lowreaches the lowest index0or thelowelement is closer toxthan thehighelement, decrease thehighindex. - If
highreaches to the highest indexarr.size()-1or it is nearer toxthan thelowelement, increase thelowindex. - The looping ends when there are exactly k elements in [low, high], the subList of which is the result.
- If
Complexity Analysis
Time complexity : O(log(n)+k)O(log(n)+k). O(log(n))O(log(n)) is for the time of binary search, while O(k)O(k) is for shrinking the index range to k elements.
Space complexity : O(k)O(k). It is to generate the required sublist.
658. Find K Closest Elements的更多相关文章
- [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绝对距离最近的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] 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 - 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 ...
- [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 ...
随机推荐
- VMware Workstation 14创建mac-10.12虚拟机详细步骤
一.VMware和unlocker的下载和安装 链接:https://pan.baidu.com/s/15Z4DqRENt6JdyfJef_VWSw 密码:40vw 1.安装VMware Works ...
- GreenPlum 安装方法详解
一.安装环境准备 1.磁盘环境准备 磁盘分区典型配置如下: 文件系统 文件格式 大小 / ext3 50GB,Linux系统的根目录,所有的目录都挂在这个目录下面,建议大小为 ...
- 一段经典的 Java 风格程序 ( 类,包 )
前言 本文给出一段经典的 Java 风格程序,请读者初步体会 Java 和 C++ 程序的不同. 第一步:编写一个类 // 将这个类打包至 testpackage 包中 package testpac ...
- 平滑的滚动listview到一个指定位
http://blog.csdn.net/w8320273/article/details/9043339
- Android UI经常使用实例 怎样实现欢迎界面(Splash Screen)
在Android平台下.下载一个应用后,首次打开映入眼帘的便是Splash Screen,暂且不说Android的设计原则提不提倡这样的Splash Screen.先来看看一般使用Splash Scr ...
- Servlet学习(1)
取得HttpSession实例 在Servlet中去个一个Session对象,可以通过HttpServletRequest接口完成. HttpSession ses = request.getSess ...
- shapes
接口 shape package shape; public abstract interface shape { public abstract void Draw(); public abstra ...
- Struts多个文件上传
Struts2多个文件上传 10级学员 韩晓爽课堂笔记 多个文件上传分为List集合和数组,下面我们着重介绍一下list集合的上传.都大同小异. 一 介绍 1. 在struts2文件上传的时候要先导入 ...
- Struts页面跳转问题
只有在web-INF中的jsp才可以不用加namespace名 <s:a action="systemIndexAction_turn" >跳转</s:a> ...
- 第三篇:python基础之数据类型与变量
阅读目录 一.变量 二.数据类型 2.1 什么是数据类型及数据类型分类 2.2 标准数据类型: 2.2.1 数字 2.2.1.1 整型: 2.2.1.2 长整型long: 2.2.1.3 布尔bool ...