lintcode460- K Closest Numbers In Sorted Array- medium

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.

Example

Given A = [1, 2, 3], target = 2 and k = 3, return [2, 1, 3].

Given A = [1, 4, 6, 8], target = 3 and k = 3, return [4, 1, 6].

Challenge  

O(logn + k) time complexity.

 

一次二分搜索find the first target. 接着迭代比较start和end,每次结束后start左移或end右移。记得处理数组边界。

 

public class Solution {
    /*
     * @param A: an integer array
     * @param target: An integer
     * @param k: An integer
     * @return: an integer array
     */
    public int[] kClosestNumbers(int[] A, int target, int k) {
        // write your code here
        //怎么传回?

        if (A == null || A.length == 0){
            return new int[0];
        }

        int[] result = new int[k];

        // find the first closest.
        int start = 0;
        int end = A.length - 1;
        while (start + 1 < end){
            int mid = start + (end - start) / 2;
            if (target <= A[mid]){
                end = mid;
            } else {
                start = mid;
            }
        }

        //compare two element in two direction iteratively.
        for (int count = 0; count < k; count++){
            if (start < 0){
                result[count] = A[end++];
            } else if (end >= A.length){
                result[count] = A[start--];
            } else if (Math.abs(A[start] - target) <= Math.abs(A[end] - target)){
                result[count] = A[start--];
            } else {
                result[count] = A[end++];
            }
        }

        return result;

    }
}

 

 

参考答案里的输入处理可以借鉴。

if (A == null || A.length == 0) {
            return A;
        }
if (k > A.length) {
            return A;
}

 

 

转载于:https://www.cnblogs.com/jasminemzy/p/7594739.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值