658. Find K Closest Elements
来源:互联网 发布:ios看书软件 编辑:程序博客网 时间:2024/06/06 01:09
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=3Output: [1,2,3,4]
Example 2:
Input: [1,2,3,4,5], k=4, x=-1Output: [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
code
时间复杂度O(logn),空间复杂度 O(1)
public class Solution { public IList<int> FindClosestElements(IList<int> arr, int k, int x) { IList<int> rtn = new List<int>(); int arrcnt = arr.Count; //count of arr if (arrcnt == 0) return rtn; int lo = 0, hi = arrcnt - 1; //find index with a nearest element to x while (hi - lo > 1) { int mid = lo + (hi - lo)/2; if (arr[mid] < x) lo = mid; else if (arr[mid] > x) hi = mid; else lo = hi = mid; } int nearestind = Math.Abs(arr[lo] - x) <= Math.Abs(arr[hi] - x) ? lo : hi; //find index range with k nearest elements to x //surrounding nearestind to find these k //by backward or forward search lo = nearestind - 1; hi = nearestind + 1; int rtncnt = 1; //count of nearest elements to x while (rtncnt++ < k){ if (hi>=arrcnt) lo--; else if (lo < 0) hi++; else{ if (Math.Abs(arr[lo] - x) <= Math.Abs(arr[hi] - x)) lo--; else hi++; } } for (int i = lo+1; i < hi; i++) rtn.Add(arr[i]); return rtn; }}
阅读全文
1 0
- 658. Find K Closest Elements
- 658. Find K Closest Elements
- 658. Find K Closest Elements
- Find K Closest Elements
- leetcode 658. Find K Closest Elements
- Leetcode 658. Find K Closest Elements
- [LeetCode] 658. Find K Closest Elements
- Binary Search:658. Find K Closest Elements
- 658. Find K Closest Elements(快排+折半查找)
- Add to List 658. Find K Closest Elements
- LeetCode:658. Find K Closest Elements程序分析
- leetcode 658. Find K Closest Elements 双指针
- Leetcode 658 Find K Closest Elements
- leetcode_658. Find K Closest Elements ? 待解决
- Find K Closest Elements问题及解法
- Find k closest elements to a given value
- Find k most repeating elements
- [LinkedIn] Find K nearest (closest) neighbors from point (comparator/comparable, priority queue )
- HomeKit开发(一)
- Linux-进程
- 简单的模拟用户登录
- Calendar
- 表存在则删除(一句sql实现)
- 658. Find K Closest Elements
- 【笔记】自定义函数库
- 淘宝开源Key/Value结构数据存储系统Tair技术剖析
- 位运算简单介绍
- javaseday20(系统类 时间 runtime math date calendar)
- AsyncTask的使用及参数、方法的介绍
- 2.1 存储空间管理 raid + lvm
- 在安装liunx下的android studios出现的错误
- linux服务器 依靠端口 关闭 服务