• 658. Find K Closest Elements


    Given a sorted array, two integers k and x, find the k closest elements to x in the array. The result should also be sorted in ascending order. If there is a tie, the smaller elements are always preferred.

    Example 1:

    Input: [1,2,3,4,5], k=4, x=3
    Output: [1,2,3,4]
    

    Example 2:

    Input: [1,2,3,4,5], k=4, x=-1
    Output: [1,2,3,4]
    

    Note:

    1. The value k is positive and will always be smaller than the length of the sorted array.
    2. Length of the given array is positive and will not exceed 104
    3. Absolute value of elements in the array and x will not exceed 104

    UPDATE (2017/9/19):
    The arr parameter had been changed to an array of integers (instead of a list of integers). Please reload the code definition to get the latest changes.

    Approach #1:

    class Solution {
    public:
        vector<int> findClosestElements(vector<int>& arr, int k, int x) {
            int len = arr.size();        
            //cout << x << " " << k << endl;
            if (x <= arr[0]) return vector<int> (arr.begin(), arr.begin()+k);
            else if (x >= arr[len-1]) return vector<int> (arr.end()-k, arr.end());
            else {
                int index = lower_bound(arr.begin(), arr.end(), x) - arr.begin();
                int low = max(0, index - k - 1), high = min(len-1, index+k-1);
                while (high - low > k - 1) {
                    if (low < 0 || (x - arr[low]) <= (arr[high] - x)) high--;
                    else if (high > len-1 || (x - arr[low]) > (arr[high] - x)) low++;
                } 
                return vector<int> (arr.begin()+low, arr.begin()+high+1);
            }
        }
    };
    

    Runtime: 72 ms, faster than 98.40% of C++ online submissions for Find K Closest Elements.

    Analysis:

    The original array has been sorted so we can take this advantage by the following steps.

    1. If the target x is less or equal than the first element in the sorted array, the first k elements are the result.
    2. Similarly, if the target x is more or equal than the last element in the sorted array, the last k elements are the result.
    3. Otherwise, we can use binary search to find the index of the element, which is equal (when this list has x) or a little bit larger than x(when this list does not have it). Then set low to its left k-1 position, and high to the right k-1 position of this index as a start. The desired k numbers must in this rang [index-k-1, index+k-1]. So we can shrink this range to get the result using the following rules.
      • If low reaches the lowest index 0 or the low element is closer to x than the high element, decrease the high index.
      • If high reaches to the highest index arr.size()-1 or it is nearer to x than the low element, increase the low index.
      • The looping ends when there are exactly k elements in [low, high], the subList of which is the result.

    Complexity Analysis

    • Time complexity : O(log(n)+k)O(log(n)+k). O(log(n))O(log(n)) is for the time of binary search, while O(k)O(k) is for shrinking the index range to k elements.

    • Space complexity : O(k)O(k). It is to generate the required sublist.

    永远渴望,大智若愚(stay hungry, stay foolish)
  • 相关阅读:
    Construct Binary Tree from Preorder and Inorder Traversal leetcode java
    win7-X64用死性不改的系统安装锐起网吧无盘V4.5 Build 3535_64位客户端老不出物理映射盘的问题
    routeros ros M ikrotik 硬件产品命名规则
    CentOS下配置常用Tunnel隧道gre,ipip
    pptp隧道断了以后,重拨也不通的情况。新any可能出现的几个问题,包括T人下线的方法
    MariaDB(mysql)+daloRADIUS 导入数据库导入用户的方法
    centos策略路由-基于源地址的策略路由ip rule
    2019年逾期率上升_24家头部P2P平台最新运营数据解读:8家近一年逾期率走势曝光
    关于逾期率你所不知道的秘密
    Vintage_坏客户定义
  • 原文地址:https://www.cnblogs.com/h-hkai/p/9929941.html
Copyright © 2020-2023  润新知