• 658. Find K Closest Elements


    Given a sorted integer array arr, two integers k and x, return the k closest integers to x in the array. The result should also be sorted in ascending order.

    An integer a is closer to x than an integer b if:

    • |a - x| < |b - x|, or
    • |a - x| == |b - x| and a < b

    Example 1:

    Input: arr = [1,2,3,4,5], k = 4, x = 3
    Output: [1,2,3,4]
    

    Example 2:

    Input: arr = [1,2,3,4,5], k = 4, x = -1
    Output: [1,2,3,4]
    

    Constraints:

    • 1 <= k <= arr.length
    • 1 <= arr.length <= 104
    • arr is sorted in ascending order.
    • -104 <= arr[i], x <= 104
    class Solution {
        public List<Integer> findClosestElements(int[] arr, int k, int x) {
            List<Integer> list = new ArrayList();
            for(int i : arr) list.add(i);
            Collections.sort(list, (a, b) -> Math.abs(a - x) - Math.abs(b - x));
            List<Integer> res = list.subList(0, k);
            Collections.sort(res);
            return res;
        }
    }

    ! 就摁用API,先按要求把list排好序。。属实妹想到,然后要多少拿多少,再排一次序。

    class Solution {
        public List<Integer> findClosestElements(int[] arr, int k, int x) {
            int lo = 0, hi = arr.length - 1;
            while(hi - lo >= k) {
                if(Math.abs(arr[lo] - x) > Math.abs(arr[hi] - x)) lo++;
                else hi--;
            }
            List<Integer> res = new ArrayList();
            for(int i = lo; i <= hi; i++) res.add(arr[i]);
            return res;
        }
    }

    用two pointers可以达到O(n), 最终lo到hi就是答案

  • 相关阅读:
    网页HTML到8.20前
    数据库SQLServer
    构建之法读后感
    VS2013 生成安装文件
    工大助手(自动化部署)
    工大助手(用户名、密码错误提示)
    工大助手(验证码错误提示)
    工大助手(加权成绩计算)
    Wireshark插件编写
    微软认知服务——人脸识别
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/14892759.html
Copyright © 2020-2023  润新知