2019盛趣笔试编程题
输入n个整数,第一个数为x,余下的数构成一个数组,求x与余下数最相近的三个数的和.
输入
2 3 6 7 -1
输出
8 (说明:3+6-1=8)
直接贴代码了
#include "stdafx.h"
#include <iostream>
#include <algorithm>
#include <vector>
#include <math.h>
using namespace std;
int n[3];
//找出最相近的三个数中最不相近的数字
int MaxInSelects(int firstNum)
{
int max = 0;
for (int i=1;i<3;i++)
{
if (abs(n[max]-firstNum) < abs(n[i]-firstNum))
max= i;
}
return max;
}
int Sum(int firstNum,vector<int> nums) {
if (nums.size()<3)
{
return NULL;
}
for (int i = 0; i < 3; i++)
{
n[i] = nums.back();
nums.pop_back();
}
int tempIndex;
for each (int vNum in nums)
{
tempIndex = MaxInSelects(firstNum);
if (abs(n[tempIndex] - firstNum) > abs(vNum - firstNum))
n[tempIndex] = vNum;
}
return n[0] + n[1] + n[2];
}
int main() {
int firstNum;
cin >> firstNum;
vector<int> nums;
int tempNum;
char getChar='a';
//只接受一行输入
while (~scanf_s("%d%c",&tempNum,&getChar))
{
nums.push_back(tempNum);
if (getChar == '\n')
break;
}
cout << Sum(firstNum, nums);
}