658. Find K Closest Elements
来源:互联网 发布:php html转字符串 编辑:程序博客网 时间:2024/06/10 05:35
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
java
class Solution { public List<Integer> findClosestElements(int[] arr, int k, int x) { Comparator<Integer> cmp = new Comparator<Integer>() { public int compare(Integer a, Integer b) { int d1 = Math.abs(a - x); int d2 = Math.abs(b - x); int diff = d2 - d1; return diff; } }; Queue<Integer> queue = new PriorityQueue<>(k, cmp); for (int i = 0; i < arr.length; i++) { if (queue.size() < k) { queue.offer(arr[i]); } else { int temp = queue.peek(); int v1 = Math.abs(temp - x); int v2 = Math.abs(arr[i] - x); if (v1 > v2) { queue.poll(); queue.offer(arr[i]); } } } List<Integer> list = new ArrayList<>(); while(!queue.isEmpty()) { list.add(queue.poll()); } Collections.sort(list); return list;}}
阅读全文
0 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 )
- 杂七杂八
- 出现( linker command failed with exit code 1)错误总结
- redispubsub
- centos7.3火狐浏览器安装flash失败后安装goole浏览器
- CGI、FastCGI和PHP-FPM关系图解
- 658. Find K Closest Elements
- Tensorflow Day19 Denoising Autoencoder
- Springmvc学习(08)-json数据交互
- sigmoid,softmax
- 浅析正则表达式-应用篇
- 微信H5房卡斗公牛网站搭建页面的过程详解
- redis sentinel实战
- 设计模式(30)--拦截过滤器模式
- 快速准确查看 android studio 3.0 功能特性方法