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;
    }
  • 相关阅读:
    JSONP
    函数式编程
    Cookie
    IE userData
    Web Storage
    前端学PHP之会话Session
    数据结构之归并排序
    数据结构之冒泡排序
    数据结构之插入排序
    数据结构之选择排序
  • 原文地址:https://www.cnblogs.com/jasminemzy/p/7594739.html
Copyright © 2011-2022 走看看