Given a target number, a non-negative integer k and an integer array A sorted in ascending order, find the k closest numbers to target in A, sorted in ascending order by the difference between the number and target. Otherwise, sorted in ascending order by number if the difference is same.

分析

先找到最接近的数字,使用Closest Number in Sorted Array中的函数,时间复杂度 O(LogN)
然后从当前位置,使用两个指针:i 和 j。分别向头尾遍历,直到 k 个元素被 add 进结果数组list,
时间复杂度O(min(k, A.length))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
public class Solution {
    /**
     * @param A an integer array
     * @param target an integer
     * @param k a non-negative integer
     * @return an integer array
     */
    public int[] kClosestNumbers(int[] A, int target, int k) {
        // Write your code here
        int len = A.length;
        int j = closestNumber(A, target), i = j - 1, di, dj;
         int[] list = new int[Math.min(k, A.length)];
        int count = 0;
        while(len-- != 0 && k-- != 0){
            di = i < 0 ? Integer.MAX_VALUE : A[i] - target;
            dj = j >= A.length ? Integer.MAX_VALUE : A[j] - target;
            if(dj == 0 || Math.abs(dj) < Math.abs(di)){
                list[count++] = A[j++];
            }
            else{
                list[count++] = A[i--];
            }
             
        }
        return list;
    }
     
    private int closestNumber(int[] A, int target) {
        // Write your code here
        if(A == null || A.length == 0)
            return -1;
        int left = 0, right = A.length - 1, mid;
        while(left < right){
            mid = left + (right - left) / 2;
            if(A[mid] < target){
                left = mid + 1;
            }
            else{
                right = mid;
            }
        }
        // when left == right, this is the first position that target can be insert
        if(right > 0 && (A[right] - target) > (target - A[right - 1]))
            return right - 1;
        else
            return right;
    }
}

K Closest Numbers In Sorted Array的更多相关文章

  1. Closest Number in Sorted Array

    Given a target number and an integer array A sorted in ascending order, find the index i in A such t ...

  2. FB面经Prepare: Merge K sorted Array

    Merge K sorted Array 跟Merge K sorted lists不同在于,从PQ里poll出来以后不知道下一个需要被加入PQ的是哪一个 所以需要写一个wrapper class p ...

  3. 【leetcode】1296. Divide Array in Sets of K Consecutive Numbers

    题目如下: Given an array of integers nums and a positive integer k, find whether it's possible to divide ...

  4. 658. Find K Closest Elements

    Given a sorted array, two integers k and x, find the k closest elements to x in the array. The resul ...

  5. [LeetCode] 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 resul ...

  6. [Swift]LeetCode658. 找到 K 个最接近的元素 | Find K Closest Elements

    Given a sorted array, two integers k and x, find the kclosest elements to x in the array. The result ...

  7. [Swift]LeetCode973. 最接近原点的 K 个点 | K Closest Points to Origin

    We have a list of points on the plane.  Find the K closest points to the origin (0, 0). (Here, the d ...

  8. Find K Closest Elements

    Given a sorted array, two integers k and x, find the k closest elements to x in the array. The resul ...

  9. LeetCode - Find K Closest Elements

    Given a sorted array, two integers k and x, find the k closest elements to x in the array. The resul ...

随机推荐

  1. Supervisor4.0和python2.7的crit问题,导致python进程阻塞

    1.问题原因 Supervisor高版本在守护python2.7的服务时,会crit并报错并倒至进程阻塞(python进程存在,但不在运行)的问题,一般会和字符集有关系 <type 'excep ...

  2. 学习笔记之ubuntu修改固定IP脚本

    一.shell脚本编程 二.正则表达式 三.linux修改IP的方法 #!/bin/bash cd /etc/network/ stty erase '^?' write_interfaces() { ...

  3. vue中的样式

    一.使用class样式: CSS部分: <style> .green{ color:green; } .italic{ font-style:italic; } .thin{ ; } .a ...

  4. python怎么安装requests、beautifulsoup4等第三方库

    零基础学习python最大的难题之一就是安装所有需要的软件,下面来简单介绍一下如何安装用pip安装requests.beautifulsoup4等第三方库:   方法/步骤     点击开始,在运行里 ...

  5. Paper Reading - Long-term Recurrent Convolutional Networks for Visual Recognition and Description ( CVPR 2015 )

    Link of the Paper: https://arxiv.org/abs/1411.4389 Main Points: A novel Recurrent Convolutional Arch ...

  6. tikv 安装

    export HostIP="127.0.0.1" docker run -d -p 2379:2379 -p 2380:2380 --name pd pingcap/pd \ - ...

  7. PS1修改xshell命令行样式

    linux 其他知识目录 在/root/.bashrc下加入如下代码. export PS1='\n\e[1;37m[\e[m\e[1;32m\u\e[m\e[1;33m@\e[m\e[1;35m\H ...

  8. kafka可靠性

    文章转载自: http://blog.csdn.net/u013256816/article/details/71091774

  9. php 通过curl上传图片

    通过curl上传图片 PHP < 5.5: 使用 目前使用的php版本 7.1 测试无法使用 前面加@ 的方法上传文件 ,查找资料 使用 curl_setopt($ch,CURLOPT_SAFE ...

  10. javascript event对象操作

    js代码: $(".leads_detail").click(function(e){ e = e || event; var t = e.target || e.srcEleme ...