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 }
  • 相关阅读:
    Android读取url图片保存及文件读取
    Adroid解析json
    接口设计的 11 种原则
    检查并创建目录mkdir
    python 替换windows换行符为unix格式
    python中 __name__及__main()__的使用
    python中的urlencode与urldecode
    CentOS Docker 安装
    CentOS基础命令大全
    ubuntu更换阿里源
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/9824960.html
Copyright © 2011-2022 走看看