zoukankan      html  css  js  c++  java
  • [leetcode]658. Find K Closest Elements绝对距离最近的K个元素

    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:

    1. The value k is positive and will always be smaller than the length of the sorted array.
    2. Length of the given array is positive and will not exceed 104
    3. Absolute value of elements in the array and x will not exceed 104

    题目

    思路

    本题要求我们在sorted array中找出K个最相近于x的数。因为输出结果一定排好序的、k-size的区间,若能找出该区间的leftBound,向右边走k个值,就可以得到desired output。

    即问题转化为,怎样找到该leftBound呢? 在[0, n-k]中使用binary search查找

    代码

     1 class Solution {
     2   public List<Integer> findClosestElements(int[] arr, int k, int x) {
     3        int begin = 0;
     4        int end = arr.length - k;
     5        while(begin < end){
     6                int mid = begin + (end - begin) /2 ; 
     7                if(x > arr[mid]){
     8                    if( x - arr[mid] > arr[mid + k] - x){
     9                        begin = mid +1;
    10                    }else{
    11                        end = mid;
    12                    }
    13                }else{
    14                    end = mid;
    15                }
    16        }
    17        int index = begin;
    18        List<Integer> result = new ArrayList<>() ;
    19        while( k != 0){
    20                result.add(arr[index++]);
    21                k--;
    22        }
    23        return result;
    24     }
    25 }
  • 相关阅读:
    linux安装oracle
    echarts柱状图,改变柱状颜色
    JS实现键盘监听(包括组合键)
    css根据屏幕大小切换样式
    (转)Win10下PostgreSQL10与PostGIS安装
    navicat连接PostgreSQL报:column “rolcatupdate” does not exist ...错误的解决办法
    大屏FAQ
    大屏介绍
    大屏模板制作
    大屏做成这样,领导不重用你都难
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/9824960.html
Copyright © 2011-2022 走看看