• 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;
        }
    }
  • 相关阅读:
    itext itextpdf 版本概要介绍
    github上的优秀项目和开发环境配置
    tfs2012 的体验地址
    Linux网卡攻略
    展现图表JavaScript库 Javascript web charts [参考地址]
    JavaEE的几个参考
    dsl boo3个例子 9
    已读的和在读的一些C++经典图书
    WinRT参考资料
    Linux性能监测工具
  • 原文地址:https://www.cnblogs.com/jasminemzy/p/9672412.html
Copyright © 2020-2023  润新知