zoukankan      html  css  js  c++  java
  • LeetCode 658. Find K Closest Elements

    原题链接在这里:https://leetcode.com/problems/find-k-closest-elements/description/

    题目:

    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

    题解:

    直接查找这k个最近值开始的位置po. 也就是arr[po] 比 arr[po+k]更接近目标值x.

    二分查找时,如果arr[po] 比 arr[po+k] 更加远离目标值,那么起始位置po肯定在当下试验位置的右侧.

    Time Complexity: O(logn + k).

    Space: O(1). regardless res.

    AC Java:

     1 class Solution {
     2     public List<Integer> findClosestElements(int[] arr, int k, int x) {
     3         List<Integer> res = new ArrayList<Integer>();
     4         if(arr == null || arr.length == 0 || k == 0){
     5             return res;
     6         }
     7         
     8         int l = 0;
     9         int r = arr.length-k;
    10         while(l<r){
    11             int mid = l+(r-l)/2;
    12             if(x - arr[mid] > arr[mid+k]-x){
    13                 l = mid+1;
    14             }else{
    15                 r = mid;
    16             }
    17         }
    18         
    19         for(int i = l; i<l+k; i++){
    20             res.add(arr[i]);
    21         }
    22         return res;
    23     }
    24 }
  • 相关阅读:
    敏捷之Scrum框架
    Google浏览器80版本以上无法打开系统页面问题
    ThreadLocal 了解
    简化两个list之间赋值操作
    linux下用命令调用dubbo服务
    13条代码审查建议
    初识MongoDB(1)
    linux日常常用命令整理
    java发起http请求
    工作思维方法
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/7949934.html
Copyright © 2011-2022 走看看