Leetcode 658. Find K Closest Elements
来源:互联网 发布:yonex 网球拍 知乎 编辑:程序博客网 时间:2024/06/03 10:58
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
使用 binary search 二分法 来找到 arr 里 x 所对应的 index, 如果 没有,idx = - (插入位置)- 1.
1, 2, 4, 5 x = 3
idx = -3, 插入位置的idx 是 2, 所以返回 -2-1 = -3
接下来的思路是运用两个指针,i,j
如果 j 到 头了 或 ( i 大于等于 0 and 右边比左边 大于或等于)i--
public List<Integer> findClosestElements(List<Integer> arr, int k, int x) { int idx = Collections.binarySearch(arr, x); idx = idx < 0 ? -(idx + 1) : idx; int j = idx, i = idx - 1; while (k-- > 0) { if (j >= arr.size() || (i >= 0 && Math.abs(x - arr.get(j)) >= Math.abs(x - arr.get(i)))) i--; else j++; } return arr.subList(i + 1, j); }
阅读全文
0 0
- leetcode 658. Find K Closest Elements
- Leetcode 658. Find K Closest Elements
- [LeetCode] 658. Find K Closest Elements
- 658. Find K Closest Elements
- 658. Find K Closest Elements
- 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
- 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 ? 待解决
- Find K Closest Elements问题及解法
- Find k closest elements to a given value
- Find k most repeating elements
- LeetCode|Top K Frequent Elements
- maven搭建和配置
- jzoj5272 神奇的重复序列 (寻找性质)
- HTML语法
- 时间复杂度和空间复杂度
- CSU-ACM2017暑期训练16-树状数组 G
- Leetcode 658. Find K Closest Elements
- 参数依赖查找
- jsp根路径,这个老见,一直没搞明白String basePath = request.getScheme()+"://"+request.getServerName()+":"+requ
- 写一个调色板控件(终结)
- URAL 1996 Cipher Message 3 (FFT + KMP)
- 多机Monkey全自动测试尝试
- 如何在mac上安装linus
- 求一个数的因子数打表
- Centos 5.5不能使用yum