zoukankan      html  css  js  c++  java
  • lintcode460

    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.

    The value k is a non-negative integer and will always be smaller than the length of the sorted array.
    Length of the given array is positive and will not exceed 10^4
    Absolute value of elements in the array and x will not exceed 10^4

    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.

    1.普通二分法找到最接近target的数。

    2.两根指针向外扩去,选绝对值小的放到结果数组里。

    细节:两根指针向外扩去的过程中注意边界越界问题,要先检测。

    我的实现

    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 start = 0; 
            int end = A.length - 1;
            
            while (start + 1 < end) {
                int mid = start + (end - start) / 2;
                if (target >= A[mid]) {
                    start = mid;
                } else {
                    end = mid;
                }
            }
            
            int[] result = new int[k];
            for (int i = 0; i < k; i++) {
                if (start < 0) {
                    result[i] = A[end];
                    end++;
                } else if (end >= A.length) {
                    result[i] = A[start];
                    start--;
                } else if (Math.abs(A[start] - target) <= Math.abs(A[end] - target)) {
                    result[i] = A[start];
                    start--;
                } else {
                    result[i] = A[end];
                    end++;
                }
            }
            
            return result;
            
        }
    }
  • 相关阅读:
    Leetcode 1. Two Sum (Python)
    视觉机器学习------KNN学习
    anaconda新建虚拟环境安装各个依赖包
    Matconvnet安装
    argparse模块
    Matconvnet笔记(一)
    Ubuntu14.04下如何安装TensorFlow
    springboot2+freemarker简单使用
    mongodb安装4.0(rpm)
    检测web界面不能访问后重启
  • 原文地址:https://www.cnblogs.com/jasminemzy/p/9442307.html
Copyright © 2011-2022 走看看