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;
            
        }
    }
  • 相关阅读:
    Python操作 RabbitMQ、Redis、Memcache、SQLAlchemy
    Django的ORM操作
    RabbitMQ
    CentOS忘记用户名或者密码解决办法
    VUE-es6
    vue基础之命令
    爬虫框架:scrapy
    爬虫高性能相关
    MongoDB
    Beautifulsoup模块
  • 原文地址:https://www.cnblogs.com/jasminemzy/p/9442307.html
Copyright © 2011-2022 走看看