跳到主要内容

1300.转变数组后最接近目标值的数组和

链接:1300.转变数组后最接近目标值的数组和
难度:Medium
标签:数组、二分查找、排序
简介:排序后进行判断,四舍五入

题解 1 - typescript

  • 编辑时间:2020-06-17
  • 执行用时:96ms
  • 内存消耗:36MB
  • 编程语言:typescript
  • 解法介绍:description。
function findBestValue(arr: number[], target: number): number {
const len = arr.length;
if (len === 1) return target > arr[0] ? target : arr[0];
arr.sort((a, b) => a - b);
let sum = 0;
let min = Infinity;
let cha = Infinity;
for (let i = 0; i < len; i++) {
const num = arr[i];
const sLen = len - i - 1;
sum += num;
const need = Math.round((target - sum) / sLen);
if (need < num || (i !== len - 1 && need > arr[i + 1])) continue;
const newCha = Math.abs(need * sLen + sum - target);
compCha(newCha, need);
const newCha2 = Math.abs((need - 1) * sLen + sum - target);
compCha(newCha2, need - 1);
}
if (min === Infinity) {
const num = Math.round(target / len);
if (num < arr[0]) {
const newCha = Math.abs(num * len - target);
compCha(newCha, num);
}
}
compCha(Math.abs(target - sum), arr[len - 1]);
return min;
function compCha(newCha: number, need: number): void {
if (newCha < cha || (newCha === cha && need < min)) {
cha = newCha;
min = need;
}
}
}