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;
        }
    }
  • 相关阅读:
    QTP err.number
    QTP参数化
    QTP基础
    QTP脚本补录
    QTP添加对象入库
    系统自带计算器自动化
    QTP安装
    App 测试
    本地化和国际化测试
    剑桥雅思写作高分范文ESSAY30
  • 原文地址:https://www.cnblogs.com/jasminemzy/p/9672412.html
Copyright © 2011-2022 走看看