zoukankan      html  css  js  c++  java
  • leetcode658

    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

    Heap。O(nlogk)
    1.存入数据:数字与x的差。
    2.heap的比较器:abs大的或者abs一样大但绝对值大的排前面跑到peek处。这些是当heap大小超过k的时候被淘汰的最弱的那个。
    3.代码流程:遍历数字加入heap,heap超过k就poll掉顶上那个。最后剩下的就是k个最近的了,加到答案里,排序,返回。

    实现:

    class Solution {
        public List<Integer> findClosestElements(int[] arr, int k, int x) {
            List<Integer> ans = new ArrayList<>();
            if (arr == null || arr.length < k) {
                return ans;
            }
            
            PriorityQueue<Integer> heap = new PriorityQueue<Integer>(new Comparator<Integer>() {
                @Override
                public int compare(Integer a, Integer b) {
                    if (Math.abs(a) != Math.abs(b)) {
                        return Math.abs(b) - Math.abs(a);
                    } else {
                        return b - a;
                    }
                }
            });
            
            for (int i = 0; i < arr.length; i++) {
                heap.offer(arr[i] - x);
                if (heap.size() > k) {
                    heap.poll();
                }
            }
            
            
            for (int i = 0; i < k; i++) {
                ans.add(heap.poll() + x);
            }
            Collections.sort(ans);
            return ans;
        }
    }
  • 相关阅读:
    替换空格
    centos虚拟机 服务器搭建
    Java 深度遍历和广度优先遍历
    idea热部署Devtools
    idea字符编码设置
    idea破解详细教程
    Java序列化
    60+Git常用命令行
    LeetCode 236. 二叉树的最近公共祖先
    08 讲解v-cloak,v-text,v-html的基本使用
  • 原文地址:https://www.cnblogs.com/jasminemzy/p/9672412.html
Copyright © 2011-2022 走看看