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;
            
        }
    }
  • 相关阅读:
    git的相关命令
    vue资料链接
    自定义小程序底部菜单
    物联网开发日记四:原理图2
    物联网开发日记三:原理图1
    物联网开发日记二:设计系统结构
    物联网开发日记一:准备工作
    mybatis不使用@Param有人报错有人却不报错问题
    最简单的js包装对象、ajax请求
    java文字转拼音、首字母缩写
  • 原文地址:https://www.cnblogs.com/jasminemzy/p/9442307.html
Copyright © 2011-2022 走看看