Leetcode 658.找到K个最接近的元素

找到k个最接近的元素

给定一个排序好的数组,两个整数 k 和 x,从数组中找到最靠近 x(两数之差最小)的 k 个数。返回的结果必须要是按升序排好的。如果有两个数与 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]

   

说明:

  1. k 的值为正数,且总是小于给定排序数组的长度。
  2. 数组不为空,且长度不超过 104
  3. 数组里的每个元素与 x 的绝对值不超过 104

   

更新(2017/9/19):
这个参数 arr 已经被改变为一个整数数组(而不是整数列表)。 请重新加载代码定义以获取最新更改。

思路

Intuitively, we can sort the elements in list arr by their absolute difference values to the target x. Then the sublist of the first k elements is the result after sorting the elements by the natural order.

 

 1 import java.util.ArrayList;
 2 import java.util.Collections;
 3 import java.util.List;
 4 
 5 class Solution {
 6     public List<Integer> findClosestElements(int[] arr, int k, int x) {
 7         List<Integer> list=new ArrayList<>();
 8         for(int number:arr){
 9             list.add(number);
10         }
11         Collections.sort(list,(a, b)->a==b?a-b:Math.abs(a-x)-Math.abs(b-x));
12         list=list.subList(0,k);
13         Collections.sort(list);
14         return list;
15     }
16 }

猜你喜欢

转载自www.cnblogs.com/kexinxin/p/10394906.html