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;
        }
    }
  • 相关阅读:
    Chrome
    给Xshell增加快速命令集
    Integer对象大小比较问题
    maven的mirror和repository加载顺序
    maven的settings.xml详解
    OAuth2.0 RFC 6749 中文
    Linux下netstat命令简单操作
    Linux里的几种不同的压缩命令小记
    [ASIS 2019]Unicorn shop
    Metasploit魔鬼训练营第一章作业
  • 原文地址:https://www.cnblogs.com/jasminemzy/p/9672412.html
Copyright © 2011-2022 走看看