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. Python中的矩阵操作

    Numpy 通过观察Python的自有数据类型,我们可以发现Python原生并不提供多维数组的操作,那么为了处理矩阵,就需要使用第三方提供的相关的包. NumPy 是一个非常优秀的提供矩阵操作的包.N ...

  2. mysql数据导到本地

    需求: 把mysql查询结果导出到txt(其他格式亦可),放在本地,供下一步使用 首先网上查了下,select * from driver into outfile 'a.txt'; 前面是你的sql ...

  3. linux 下 mysql安装和配置

    最近在学习R语言,看到R与数据库交互这一部分,就自己动手实践了一下,数据库选择的是mysql,主要记录下linux下怎么安装mysql. 网上的很多资料都有相关的文章,这里只是记录下自己安装过程中遇到 ...

  4. Spring Bean注册解析(一)

           Spring是通过IoC容器对Bean进行管理的,而Bean的初始化主要分为两个过程:Bean的注册和Bean实例化.Bean的注册主要是指Spring通过读取配置文件获取各个bean的 ...

  5. nginx响应client的处理机制

    nginx与apache的不同响应机制——epoll nginx可以处理上百万级别的并发请求就是源至于异步非阻塞的处理机制,异步非阻塞核心即是epoll nginx内部反向代理

  6. [leetcode-915-Partition Array into Disjoint Intervals]

    Given an array A, partition it into two (contiguous) subarrays left and right so that: Every element ...

  7. Python3【基础】-表达式与运算符

    一.什么是表达式? 1+2*3就是一个表达式,这里的加号和乘号叫做运算符,1.2.3叫做操作数.1+2*3计算的结果是7,计算结果可以存到一个变量中,即:res = 1 + 2 * 3. 所谓的表达式 ...

  8. Alpha冲刺——第五天

    Alpha第五天 听说 031502543 周龙荣(队长) 031502615 李家鹏 031502632 伍晨薇 031502637 张柽 031502639 郑秦 1.前言 任务分配是VV.ZQ. ...

  9. 2nd scrum站立会议

    scrum站立会议 站立会议是让团队成员每日面对面站立互相交流他们所承担任务的进度.它的一个附带好处是让同组成员了解到工作的情况.本质上是为了团队交流,不是会议报告. 站立会议的目的: 1.让整个团队 ...

  10. mybatis_mysql

    SELECT round(avg(c.AVG_DELAY_TIME)) as AVG_DELAY FROM `result_road_saturation_day` a LEFT JOIN info_ ...