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. scikit-learn API

    scikit-learn API 这是scikit-learn的类和函数参考.有关详细信息,请参阅完整的用户指南,因为类和功能原始规格可能不足以提供有关其用途的完整指南. sklearn.base:基 ...

  2. [python]序列的重复操作符

    当你需要需要一个序列的多份拷贝时,重复操作符非常有用,它的语法如下: sequence * copies_int In [1]: a = [1,2,3,4] In [2]: a * 5 Out[2]: ...

  3. java 不同数据类型的相互转化

    在工作中经常会遇到需要将数据类型转化的情况,今天抽出时间总结一下. date——string Date date = new Date(); DateFormat dateformat = new S ...

  4. java面向对象的栈 队列 优先级队列的比较

    栈 队列 有序队列数据结构的生命周期比那些数据库类型的结构(比如链表,树)要短得多.在程序操作执行期间他们才被创建,通常用他们去执行某项特殊的任务:当完成任务之后,他们就会被销毁.这三个数据结构还有一 ...

  5. HUST学期助教总结

    春节还没过完,在回广州的高铁上收到是否愿意担任一次软测助教的询问.想了一天,答应了.而内心其实是有点恐慌的,有几点原因: 大学从来没有学过软件测试这门课程.对于自己的软件测试只是体系并不是很有自信. ...

  6. 《C》数组

    数组 数组方法: var arr = [1, 2, 3]; arr.push(4)://arr='[1, 2, 3, 4]' 向末尾添加一个或者多个元素 arr.pop()://删除末位元素 var ...

  7. 团队开发--NABCD

    团队成员介绍: 李青:绝对的技术控,团队中扮演“猪”的角色,勤干肯干,是整个团队的主心骨,课上紧跟老师的步伐,下课谨遵老师的指令,课堂效率高,他的编程格言“没有编不出来的程序,只有解决不了的bug”. ...

  8. Requests库与HTTP协议

    了解HTTP协议 请求与响应模式的协议: 用户提出对URL(用来定位网络中的资源位置)地址数据的操作请求,服务器给予相应. 无状态的应用层协议:两次请求之间不会互相影响. HTTP协议支持的请求种类: ...

  9. 寒假MOOC学习计划

    我选择的是西北工业大学的课程,理由如下: 首先,选择这门课的网友还蛮多的,特意看了一下评价,也不错: 其次,这个课程的排版与我从图书馆借来的一本书内容排版比较符合,可以结合起来一起看,说不定会有更多收 ...

  10. HttpWebRequest下载文件,乱码问题解决方案

    写在前面 今天之所以会总结HttpWebRequest下载文件,主要是因为在使用该类下载文件的时候,有些地方需要注意一下,在实际的项目中遇到过这种问题,觉得还是有必要总结一下的.在下载文件时,最常见的 ...