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. Spring学习(二)-----eclipse新建spring项目

    一:准本工作(下载需要的jar包) 1.下载准备Spring-framework-4.2.0 链接为: http://repo.springsource.org/libs-release-local/ ...

  2. SICP读书笔记 1.2

    SICP CONCLUSION 让我们举起杯,祝福那些将他们的思想镶嵌在重重括号之间的Lisp程序员 ! 祝我能够突破层层代码,找到住在里计算机的神灵! 目录 1. 构造过程抽象 2. 构造数据抽象 ...

  3. Smokeping配置

    参考文档: 官网:http://oss.oetiker.ch/smokeping/ 参考:http://jaminzhang.github.io/monitoring/smokeping-deploy ...

  4. Jenkins之Sonar 代码检查

    一.简介 SonarQube 是一个用于代码质量管理的开放平台.通过插件机制,Sonar 可以集成不同的测试工具,代码分析工具,以及持续集成工具.与持续集成工具(例如 Hudson/Jenkins 等 ...

  5. Kafka安装之二 在CentOS 7上安装Kafka

    一.简介 Kafka是由Apache软件基金会开发的一个开源流处理平台,由Scala和Java编写.Kafka是一种高吞吐量的分布式发布订阅消息系统,它可以处理消费者规模的网站中的所有动作流数据. 这 ...

  6. 微软职位内部推荐-Principal Development Lead - SharePoint

    微软近期Open的职位: SharePoint is a multi-billion dollar enterprise business that has grown from an on-prem ...

  7. Python如何对折线进行平滑曲线处理?

    在用python绘图的时候,经常由于数据的原因导致画出来的图折线分界过于明显,因此需要对原数据绘制的折线进行平滑处理,本文介绍利用插值法进行平滑曲线处理: 实现所需的库 numpy.scipy.mat ...

  8. CSS3 使用 calc() 计算高度 vh px

    Viewport    viewport:可视窗口,也就是浏览器.    vw Viewport宽度, 1vw 等于viewport宽度的1%    vh Viewport高度, 1vh 等于view ...

  9. Myeclipse错误:Errors occurred during the build. Errors running builder 'DeploymentBuilder' on project ...解决方法

    解决办法:1.首先关闭MyEclipse工作空间.2.然后删除工作空间下的“/.metadata/.plugins/org.eclipse.core.runtime/.settings/com.gen ...

  10. Swift-setValuesForKeysWithDictionary

    重写 setValuesForKeysWithDictionary 那么字典中可以有的字段在类中没有对应属性 class Person : NSObject { var age :Int = // 重 ...