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     }
  • 相关阅读:
    高性能分布式计算与存储系统设计概要
    .NET核心代码保护策略
    Web 通信 之 长连接、长轮询(long polling)
    C++数据结构之二叉查找树(BST)
    T4:T4 笔记 + Trait 示例
    腾讯2014软件开发
    CSS选择器从右向左的匹配规则
    Js面向对象编程
    Js杂谈-正则的测试与回溯次数
    Microsoft Message Analyzer (微软消息分析器,“网络抓包工具
  • 原文地址:https://www.cnblogs.com/wzj4858/p/7723897.html
Copyright © 2011-2022 走看看