LeeCode刷题-中等-转变数组后最接近目标值的数组和
题目描述: 给你一个整数数组 arr 和一个目标值 target ,请你返回一个整数 value ,使得将数组中所有大于 value 的值变成 value 后,数组的和最接近 target (最接近表示两者之差的绝对值最小)。 如果有多种使得和最接近 target 的方案,请你返回这些整数中的最小值。请注意,答案不一定是 arr 中的数字。来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sum-of-mutated-array-closest-to-target
示例见立扣。
刚看到这个题,大概搜了搜,发现大家用的都是什么三叉树之类的,没了解不懂,于是想到了个偷鸡的方法。
事实证明,偷鸡是不可能给过的。。。
但还是写写思路吧,之后再修改。
解题思路:暴力搜索,for循环遍历就完事了。(这里循环换成二分查找不知道时间会不会超限。先码着,之后试了再更新把)
#include<cmath>
class Solution {
public:
int size ;
int findBestValue(vector<int>& arr, int target) {
size = arr.size();
sort(arr.begin(), arr.end());
//max min
if(arr[size-1]*size<=target)
return arr[size-1];
else if(arr[0]*size>=target)
{
int temp = target/size;
if(target - temp*size<=(temp+1)*size-target)
return temp;
else
return temp+1;
}
else
{
int value=arr[0];
int i;
int dif = abs(size*arr[0]-target);
int absDif;
for(i=arr[0]+1;i<=arr[size-1];i++)
{
absDif = abs(sum(arr,i)-target);
if(absDif<dif)
{
dif = absDif;
value = i;
}
}
return value;
}
}
int sum(vector<int>& arr, int value)
{
int res=0;
int i;
for(i=0;i<size;i++)
{
if(arr[i]<=value)
res+=arr[i];
else
res+=value;
}
return res;
}
};
。。。。。。。。。。。。。。。我。是。分。割。线。。。。。。。。。。。。。。。
更新:
class Solution
{
public: int findBestValue(vector<int>& arr, int target)
{
sort(arr.begin(), arr.end());
int pre=0;
int res=arr.size();
double temp;
for(i=0; i<arr.size(); i++)
{
temp = (double)(target-pre)/res;
if(temp<=arr[i])
{ if(temp-int(temp)>=0.5)
return int(temp+1;
return int(temp);
}
pre+=arr[i];
res--;
}
return arr[arr.size()-1];
}
};
- 原理明天在写吧