码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode 658. Find K Closest Elements

时间:2017-08-16 19:09:02      阅读:196      评论:0      收藏:0      [点我收藏+]

标签:原来   ++   always   vector   sorted   back   span   close   not   

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

题目大意:求离x最近的k元素,注意输出的是值,而不是下标。并且按照升序列输出。

麻烦不要再爬我博客了。“IT大道“你妹的。

思路就是,每个元素与x做差并记录下标,按差值排序,然后再找到原来的数组的值,排序输出就行了、

class Solution {
public:
    vector<int> findClosestElements(vector<int>& arr, int k, int x) {
        int n = arr.size();
        vector<pair<int, int>> vp;
        for (int i = 0; i < n; ++i) {
            int w = abs(arr[i] - x);
            vp.push_back({w,i});
        }
        sort(vp.begin(), vp.end());
        
        vector<int>v;
        for (int i = 0; i < k ; ++i) {
            v.push_back(arr[vp[i].second]);
        }
        sort(v.begin(), v.end());
        return v;
    }
};

 

leetcode 658. Find K Closest Elements

标签:原来   ++   always   vector   sorted   back   span   close   not   

原文地址:http://www.cnblogs.com/pk28/p/7374920.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!