2021-3-13-找离x最近的k个数

题目描述:
给定一个排序好的数组,两个整数 k 和 x,
从数组中找到最靠近 x(两数之差最小)的 k 个数。
返回的结果必须要是按升序排好的。
如果有两个数与 x 的差值一样,优先选择数值较小的那个数。
输入描述:
第一行为排序好的数组arr
第二行为查找的个数k
第三行为基准值x
输出描述:
按升序排好的的数组
例如:
输入
1,2,3,4,5
4
3

#include <vector>
#include <iostream>
#include <string>
using namespace std;

vector<int> findClosestElement(vector<int> arr, int k, int x)
{
	vector<int> res;
	int len = arr.size(); 
	int left = 0;
	int right = len - 1;

	while (len > k)
	{
		if (abs(arr[left] - x) > abs(arr[right] - x))
		{
			left++; 
		}
		else
		{
			right++;
		}
		len--;
	}

	for (int i = left; i <= right; i++)
	{
		res.push_back(arr[i]);
	}

	return res;
}
int main()
{
	vector<int>arr;
	string str;
	getline(cin, str);

	while (str.find(' ') != -1)
	{
		int pos = str.find(' ');
		int num = stoi(str.substr(0, pos));
		arr.push_back(num);
		str = str.substr(pos + 1);
	}
	arr.push_back(stoi(str));
	int k = 4;
	cin >> k;
	int x = 3;
	cin >> x;
	vector<int> res = findClosestElement(arr, k, x);
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值