zoukankan      html  css  js  c++  java
  • 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就是答案

  • 相关阅读:
    委托事件
    泛型
    栈和队列
    泛型
    枚举与位枚举
    数组 集合
    .NET Framework 简介
    三行代码 完美解决word标签文字替换 POI增强版 可插入图片
    Github国内镜像网站,解决Github访问的神器
    Eureka
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/14892759.html
Copyright © 2011-2022 走看看