class Solution {
public int findBestValue(int[] arr, int target) {
int length = arr.length;
Arrays.sort(arr);
int minindex = -1;
int mincount = -1;
for(int i=0;i<=target;i+=1){
int count = 0;
for(int k=0;k<length;k+=1){
int num = arr[k];
if(num>i){
count += (length-k)*i;
break;
}
else{
count +=arr[k];
}
}
if(count == target){
return i;
}
if(minindex == -1){
minindex = i;
mincount = count;
}
else{
if(Math.abs(mincount-target)>Math.abs(count-target)){
minindex = i;
mincount = count;
}
}
}
return minindex;
}
}
leetcode-双周赛的题目
其实看到数组的题,特别是这种元素总和之类,如果对数组进行排序后不会影响题意,那么排序肯定是能对求解有帮助的。
当然,我的算法虽然能ac,但时间复杂度较高,其他选手有用二分查找的。