zoukankan      html  css  js  c++  java
  • 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;
    }
  • 相关阅读:
    [GXYCTF2019]BabyUpload
    [GYCTF2020]Blacklist
    [极客大挑战 2019]HardSQL
    PHP实现MVC框架路由功能模式
    色环电阻的阻值识别
    python的内存回收机制
    配置Openfiler做ISCS实验
    windows server 2008r2 在vmware里自动关机
    VMware Workstation网络修改vlan id值
    linux的服务自动启动的配置
  • 原文地址:https://www.cnblogs.com/jasminemzy/p/7594739.html
Copyright © 2011-2022 走看看