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     }
  • 相关阅读:
    L1-049 天梯赛座位分配​​​​​​​
    L1-046 整除光棍 大数除法
    天梯赛 L1-043 阅览室
    Hdu 1022 Train Problem I 栈
    蓝桥杯 历届试题 格子刷油漆  (动态规划)
    第九届蓝桥杯省赛真题 日志统计
    2018年第九届蓝桥杯第7题 螺旋折线
    2018年第九届蓝桥杯省赛 递增三元组
    蓝桥杯 历届试题 高僧斗法  (尼姆博弈)
    K-th Number
  • 原文地址:https://www.cnblogs.com/wzj4858/p/7723897.html
Copyright © 2011-2022 走看看