LintCode-460. Find K Closest Elements

南大计算机2024保研笔试:编译原理等5门专业课考点分布与408复习避坑指南 本文详细解析了南京大学计算机2024保研笔试的考点分布与复习策略,重点突出编译原理(占比28%-32%)和离散数学的特色考核。提供跨课程复习方法、真题题型分析及高效备考建议,帮助考生突破传统408框架,应对南大独特的命题风格。 阅读详情
  1. Find K Closest Elements

Given target, 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
Example 1:

Input: A = [1, 2, 3], target = 2, k = 3
Output: [2, 1, 3]
Example 2:

Input: A = [1, 4, 6, 8], target = 3, k = 3
Output: [4, 1, 6]
Challenge
O(logn + k) time

Notice
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^410
​4
​​
Absolute value of elements in the array will not exceed 10^410
​4
​​
解法1:
先用searchInsert()找到应该插入的位置,然后用两个指针从中间往前后找,直到找到K个数。

代码如下:

    int searchInsert(vector<int>& nums, int target) {
        if (nums.size()==0) return -1;
        
        int start=0, end=nums.size()-1;
        
        while(start+1<end) {
            int mid=start+(end-start)/2;
            if (nums[mid]==target) 
                return mid;
            else if (nums[mid]<target)
                start=mid;
            else
                end=mid;
        }

        if (nums[start]>=target) return start;
        if (nums[end]<target) return end+1;
        return end;    
    }
    
    vector<int> kClosestNumbers(vector<int> &A, int target, int k) {
        vector<int> result;
        if (k>A.size()) return result;

        int pos = searchInsert(A, target);
        int p1, p2;
        if (pos == 0) {
            p1=0; p2=1;
        } else {//if (pos == A.size()) {
            p1=pos-1; p2=pos;
        } 
       
        int count=0;
        while(count<k && p1>=0 && p2<A.size()) {
            if ((target-A[p1]) <= (A[p2]-target)) {//note <=here
                result.push_back(A[p1--]);
            } else {
                result.push_back(A[p2++]);
            }
            count++;
        }
        while(count<k) {
            if (p1<0) {
                result.push_back(A[p2++]);
            } else {
                result.push_back(A[p1--]);
            }
            count++;
        }    
    
        return result;
    }

注意:

  1. 当一边已经找完则剩下的全部从另一边找
  2. 当insertPos在边界上时要注意。

Some test cases:

  1. test case 1:
    [1,4,6,10,20]
    21
    4
  2. test case 2:
    [1,10,15,25,35,45,50,59]
    30
    7

二刷:

class Solution {
public:
    /**
     * @param a: an integer array
     * @param target: An integer
     * @param k: An integer
     * @return: an integer array
     */
    vector<int> kClosestNumbers(vector<int> &a, int target, int k) {
        vector<int> res;
        int start = 0, end = a.size();
        
        while (start + 1 < end) {
            int mid = start + (end - start) / 2;
            if (a[mid] < target) {
                start = mid;
            } else {
                end = mid;
            }
        }
        int pos;
        if (target - a[start] <= a[end] - target) pos = start;
        else pos = end;
        int numElems = 0;
        int left = pos, right = pos + 1;
        
        while (numElems < k) {
            if (left >= 0 && right <= a.size() - 1) {
                if (target - a[left] <= a[right] - target) {
                    res.push_back(a[left]);
                    left--;
                } else {
                    res.push_back(a[right]);
                    right++;
                }
            } else if (left >= 0) {
                res.push_back(a[left]);
                left--;
            } else {
                res.push_back(a[right]);
                right++;
            }
            numElems++;
        }
        return res;
    }
};

三刷:
没有用二分法,直接用左右两个指针一左一右向中间靠近,直到两个指针中间距离为k。这个效率低些。

class Solution {
public:
    /**
     * @param a: an integer array
     * @param target: An integer
     * @param k: An integer
     * @return: an integer array
     */
    vector<int> kClosestNumbers(vector<int> &a, int target, int k) {
        int len = a.size();
        int start = 0, end = len - 1;
        while (end - start + 1 > k) {
            if (abs(a[start] - target) <= abs(a[end] - target)) {
                end--;
            } else {
                start++;
            }
        }
        vector<int> res(k, 0);
        while (k > 0) {
            if (abs(a[start] - target) > abs(a[end] - target)) {
                res[k - 1] = a[start];
                start++;
            } else {
                res[k - 1] = a[end];
                end--;
            }
            k--;
        }
        return res;
    }
};

四刷:注意用二分法是先找到最左侧的那个等于x的数,如果找不到就在start和end中找更接近x的那个。
为什么是最左侧?Otherwise, sorted in ascending order by number if the difference is same.

class Solution {
public:
    vector<int> findClosestElements(vector<int>& arr, int k, int x) {
        int n = arr.size();
        int start = 0, end = n - 1, count = 0;
        while (start + 1 < end) {
            int mid = start + (end - start) / 2;
            if (arr[mid] < x) {
                start = mid;
            } else {
                end = mid;
            }
        }
        int pos = start;
        if (abs(arr[start] - x) < abs(arr[end] - x)) pos = start;
        else pos = end;
        vector<int> res;
        start = pos - 1, end = pos;
        while (count < k && start >= 0 && end < n) {
            if (abs(arr[start] - x) <= abs(arr[end] - x)) {
                res.push_back(arr[start]);
                start--;
            } else {
                res.push_back(arr[end]);
                end++;
            }
            count++;
        }
        while (count < k && start >= 0) {
            res.push_back(arr[start--]);
            count++;
        }
        while (count < k && end < n) {
            res.push_back(arr[end++]);
            count++;
        }
        sort(res.begin(), res.end());
        return res;
    }
};
是德频谱分析仪相位噪声测量实战指南:从原理到精准操作 本文详细介绍了是德频谱分析仪在相位噪声测量中的实战操作指南,从基础概念到高级技巧全面解析。通过5G基站时钟测量等实际案例,展示如何利用是德N9030B等设备精准测量相位噪声,并分享设备预热、参数设置、环境干扰排除等关键操作要点,帮助工程师提升测量精度和效率。 阅读详情

相关推荐

Oracle Primavera P6实战手册:从入门到精通的企业项目管理秘籍

本文详细介绍了Oracle Primavera P6在企业项目管理中的实战应用,从环境配置到高级进度控制技巧,帮助用户从入门到精通。通过WBS设计、资源优化和情景模拟等核心功能,提升项目管理效率。特别适合需要处理复杂项目和多团队协作的企业用户。

weixin_29235923的博客 280

Find K Closest Elements

Given a sorted array, two integerskandx, find thekclosest elements toxin the array. The result should also be sorted in ascending order. If there is a tie, the smaller elements are always prefer...

Czyaun的博客 223

MobaXterm破解14个会话限制的保姆级教程(附Python环境配置指南)

本文提供了MobaXterm破解14个会话限制的详细教程,并深入讲解了如何配置稳定的Python环境以支持相关脚本运行。通过理解软件授权机制、安全实践步骤以及许可文件的应用,帮助用户解除会话数量限制,实现高效的远程服务器管理与自动化运维。

weixin_29211309的博客 1795

leetcode 658. Find K Closest Elements

https://leetcode.com/problems/find-k-closest-elements/ 给定一个已排序的数组,以及整数x和整数k,找到数组中最接近x的k个元素存在一个列表中返回。 当有两个元素跟x的差距一样时,优先选择比较小的元素。 一、问题分析 测试用例: Input: [1,2,3,4,5], k=4, x=3 Output: [1,2,3,4] I...

小景的博客 199

DSP TMS320FF28335程序从FLASH中拷贝到RAM中的两种方法及FLASH烧写方法

程序从FLASH中拷贝到RAM中执行的方法 DSP的程序下载执行方式有两种:一种是下载到RAM中在线执行,一种是下载到FLASH中执行。在RAM中执行时,具有执行速度快,可以无限次下载的特点,但是RAM的特点是掉电丢失数据。FLASH具有掉电不丢失数据的特点,但是同时存在执行速度慢和擦写次数有限的缺点。因此综合两者的特点,在DSP的开发过程中一般会结合使用两者。在前期程序调试过程,由于需要频繁的

AEECREN的博客 1万+

顶尖高校强化学习课的隐性知识体系与工程落地路径

强化学习(RL)本质上是构建可控因果闭环的决策建模方法,其核心不在算法公式本身,而在于马尔可夫决策过程(MDP)的严谨建模、奖励函数设计的因果约束,以及策略优化中的方差-偏差权衡。从理论角度看,RL需融合随机过程、凸优化与控制系统知识;从工程实践看,它高度依赖环境仿真 fidelity、GPU内存访问模式与数值稳定性控制。当前主流教程普遍缺失‘环境即课程’‘reward即先验’‘超参即物理量纲’等关键认知范式,导致大量开发者陷入reward collapse、训练不收敛、代码不可移植等典型陷阱。本文聚焦伯克

cm333666的博客 416

lintcode460- K Closest Numbers In Sorted Array- medium

Given a target number, a non-negative integerkand 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 num...

weixin_30677617的博客 144

细胞膜电学特性的分数阶微积分建模

分数阶微积分在细胞膜电学特性建模中的应用主要体现在对细胞膜的电容行为和神经元放电活动的更精确描述上。

冰河世纪20的博客 635

Leetcode日练5 #658 Find K closest element

#658 Find K Closest Elements Given a sorted integer array arr, two integers k and x, return the k closest integers to x in the array. The result should also be sorted in ascending order. An integer a is closer to x than an integer b if: |a - x| < |b

Bittersweet_t的博客 477

UG\NX二次开发 判断对象是虚线还是实线

网友提问“怎么区分虚线实线”,这个可以通过函数判断。

王牌飞行员_里海的博客 367

RK3588 平台部署实战:OpenCV + LibTorch + FFmpeg 环境搭建与深度学习推理全流程解析

现在,你已经掌握了在RK3588上搭建OpenCV+LibTorch+FFmpeg环境的完整流程,也完成了深度学习模型的部署测试。不妨从一个具体的应用场景入手(如检测自家宠物的品种),亲手打造属于你的第一个边缘智能应用——当你看到模型在RK3588上精准输出结果时,你会发现:嵌入式深度学习的门槛,其实并没有想象中那么高。这些依赖是编译OpenCV、FFmpeg的基础,安装过程中若提示权限不足,可在命令前加。若能输出预测的类别索引,则说明环境搭建成功,模型推理流程通畅。文件,实现模型加载、图像预处理与推理。

FJN110的博客 551

[LeetCode] 658. Find K Closest Elements

题目链接: https://leetcode.com/problems/find-k-closest-elements/description/ DescriptionGiven a sorted array, two integers k and x, find the k closest elements to x in the array. The result should also be

从入门到扑街 1585

一个 ABAP 工具,能打印系统里某个用户对 BSP 应用的浏览历史记录

只要一个用户在 SAP ABAP 系统里浏览过 BSP 页面,会留下浏览历史记录。本工具会解析出这些记录,打印出该用户浏览的历史事件,和浏览过的页面名称。

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 555

【Lintcode】460. Find K Closest Elements

题目地址: https://www.lintcode.com/problem/find-k-closest-elements/description 给定一个升序数组AAA,再给定一个目标数ttt,和一个非负整数kkk,找离ttt最近的kkk个整数。需要按照与ttt的接近程度从小到大排序。如果一样接近,则小的排在前面。 首先,离ttt最近的kkk个数一定在AAA中位置连续(反证法可证),我们可以对这kkk个数的左端点(下称合法区间左端点)位置进行二分。设左端点一开始的范围是[l,r][l,r][l,r],显

数学、算法爱好者的博客 231

NTscan扫描工具

ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。

温度PID控制PLC程序

温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值

lintcode460 - Find K Closest Elements

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 num...

weixin_30375247的博客 143

Camera2Demo

在Camera2 的基础上进行封装,使得Camera2一堆初始化逻辑与Activity分离,降低耦合度,完成预览拍照并保存的操作

Find K Closest Elements 发现K最近的元素

给定一个有序数组,两个整数k和x,找到数组中最接近x的元素。 结果也应按升序排序。 如果有平局,小元素总是首选。例1:输入:[1,2,3,4,5],k = 4,x = 3输出:[1,2,3,4]例2:输入:[1,2,3,4,5],k = 4,x = -1输出:[1,2,3,4]注意:值k是正数,并且总是小于排序数组的长度。给定数组的长度是正数,不会超过104数组和x中元素的绝对值不会超过104思路...

qq_26410101的博客 659

【疑问】leetcode - 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 al

课桌 2055

leetcode 658. Find K Closest Elements 寻找绝对距离最近K个元素+ 双指针遍历

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 prefe...

JackZhangNJU的专栏 1292

[leetcode] 658. Find K Closest Elements

Description 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 ...

Learning from the mistakes 391

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 prefe...

学习应该是一个长链接 321

[leetcode]658. Find K Closest Elements

链接:https://leetcode.com/problems/find-k-closest-elements/description/ Given a sorted array, two integerskandx, find thekclosest elements toxin the array. The result should also be

xiaocong1990的博客 255

【两次过】Lintcode 460. 在排序数组中找最接近的K个数

给一个目标数 target, 一个非负整数k, 一个按照升序排列的数组 A。在A中找与target最接近的k个整数。返回这k个数并按照与target的接近程度从小到大排序,如果接近程度相当,那么小的数排在前面。 样例 如果 A =[1, 2, 3], target =2and k =3, 那么返回[2, 1, 3]. 如果 A =[1, 4, 6, 8], target =3...

majichen95的博客 1619

Find k closest elements to a given value

Given a sorted array arr[] and a value x, find the k closest elements to x in arr

石林在HAYS搬砖。 839

[Leetcode] 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

魔豆(Magicbean)的博客 415

[LeetCode] Find K Closest Elements

Given a sorted array, two integerskandx, find thekclosest elements toxin the array. The result should also be sorted in ascending order. If there is a tie, the smaller elements are always prefe...

weixin_30521161的博客 190

lintcode460. 在排序数组中找最接近的K个数

给一个目标数 target, 一个非负整数 k, 一个按照升序排列的数组 A。在A中找与target最接近的k个整数。返回这k个数并按照与target的接近程度从小到大排序,如果接近程度相当,那么小的数排在前面。 样例 样例 1: 输入: A = [1, 2, 3], target = 2, k = 3 输出: [2, 1, 3] 样例 2: 输入: A = [1, 4, 6, 8], tar...

sinb妃的博客 250

[leetcode] 658. Find K Closest Elements @ python

原题 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 pr...

闲庭信步 370
上一篇: LintCode-585. Maximum Number in Mountain Sequence
下一篇: LintCode-447. Search in a Big Sorted Array
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址