zoukankan      html  css  js  c++  java
  • 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

    题目含义:给定一个排序数组,两个整数k和x,求数组中距离x最近的k个数字。结果应该有序,距离相同时优先选择较小的数字。

     1     public List<Integer> findClosestElements(int[] arr, int k, int x) {
     2 //        由于数组是有序的,所以最后返回的k个元素也一定是有序的,那么其实就是返回了原数组的一个长度为k的子数组,转化一下,
     3 //        实际上相当于在长度为n的数组中去掉n-k个数字,而且去掉的顺序肯定是从两头开始去,应为距离x最远的数字肯定在首尾出现。
     4 //        那么问题就变的明朗了,我们每次比较首尾两个数字跟x的距离,将距离大的那个数字删除,直到剩余的数组长度为k为止
     5         List<Integer> list =new ArrayList<Integer>();
     6         for (int i=0;i<arr.length;i++)
     7         {
     8             list.add(arr[i]);
     9         }
    10         while (list.size() > k) {
    11             int first  = 0, last = list.size() - 1;
    12             if (x - list.get(first) <= list.get(last) - x) {
    13                list.remove(last);
    14             } else {
    15                 list.remove(first);
    16             }
    17         }
    18         return list;        
    19     }
  • 相关阅读:
    和程序员有关的对联
    《kali linux 渗透测试初级教程》免费下载
    PPT嵌入字体的方法
    修改nw.js的exe文件使其请求管理员权限
    nw.js FrameLess Window下的窗口拖拽与窗口大小控制
    nw.js如何处理拖放操作
    nw.js 软件推荐:AxeSlide斧子演示:PPT的另一种可能(转)
    c#使用word、excel、pdf ——转
    ASP.NET MVC
    http 报文
  • 原文地址:https://www.cnblogs.com/wzj4858/p/7723897.html
Copyright © 2011-2022 走看看