• 【Java|golang】658. 找到 K 个最接近的元素


    给定一个 排序好 的数组 arr ,两个整数 k 和 x ,从数组中找到最靠近 x(两数之差最小)的 k 个数。返回的结果必须要是按升序排好的。

    整数 a 比整数 b 更接近 x 需要满足:

    |a - x| < |b - x| 或者
    |a - x| == |b - x| 且 a < b

    示例 1:

    输入:arr = [1,2,3,4,5], k = 4, x = 3
    输出:[1,2,3,4]
    示例 2:

    输入:arr = [1,2,3,4,5], k = 4, x = -1
    输出:[1,2,3,4]

    提示:

    1 <= k <= arr.length
    1 <= arr.length <= 104
    arr 按 升序 排列
    -104 <= arr[i], x <= 104

    public List<Integer> findClosestElements(int[] arr, int k, int x) {
            List<Integer> res = new ArrayList<>();
            int max=Math.abs(arr[0]-x);
            res.add(arr[0]);
            for (int i = 1; i < arr.length; i++) {
                if(res.size()==k){
                    int temp=Math.abs(arr[i]-x);
                    if(temp>max){
                        return res;
                    }else if(temp==max){
                        continue;
                    }
                    res.remove(0);
                }
                res.add(arr[i]);
                max=Math.abs(res.get(0)-x);
            }
            return res;
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    在这里插入图片描述

    func findClosestElements(arr []int, k int, x int) []int {
    	res := make([]int, 0)
    	max := math.Abs(float64(arr[0] - x))
    	res = append(res, arr[0])
    	for i:=1;i< len(arr);i++ {
    		if len(res)==k{
    			temp := math.Abs(float64(arr[i] - x))
    			if temp>max {
    				return res
    			}else if temp==max {
    				continue
    			}
    			res=res[1:]
    		}
    		res = append(res, arr[i])
    		max = math.Abs(float64(res[0] - x))
    	}
    	return res
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    在这里插入图片描述

  • 相关阅读:
    2023年7月工作经历二
    什么是位域和位段?如何定义和使用位域?
    7、MySQL Workbench 导出导入数据库
    降温无叶风扇出口英国UKCA办理内容
    springboot银行客户管理系统毕业设计源码250903
    Golang string 常用方法
    bukku ctf(刷题2)
    余额宝收益怎么算
    面向对象的封装、继承、多态
    yaml数据格式
  • 原文地址:https://blog.csdn.net/qq_44461217/article/details/126518912