leetcode-1300-转变数组后最接近目标值的数组和
作者:互联网
题目描述:
解法一:二分法 提交:O(nlogn)
class Solution: def findBestValue(self, arr: List[int], target: int) -> int: def helper(num): res = 0 for i in arr: if i > num: res += num else: res += i return res l,r = 0,min(target,max(i for i in arr)) while l + 1 < r: mid = l - (l-r)//2 if helper(mid) < target: l = mid else: r = mid if abs(helper(l) - target) > abs(helper(r) - target): return r else: return l
方法二:排序 提交: O(nlogn)
class Solution: def findBestValue(self, arr: List[int], target: int) -> int: arr.sort() n = len(arr) tmp = 0 for i in range(n): if tmp + arr[i] * n < target: tmp += arr[i] n -= 1 elif tmp + arr[i] * n < target: return arr[i] else: t = target - tmp ans = t // n if t - ans * n <= (ans + 1) *n - t: return ans else: return ans + 1 return arr[-1]
java:
class Solution { public int findBestValue(int[] arr, int target) { Arrays.sort(arr); int len = arr.length; int curSum = 0; for (int i = 0; i < len; i++) { int curAve = (target - curSum) / (len - i); if (curAve <= arr[i]) { //即判断curAve两边 double curAveDou = (target * 1.0 - curSum) / (len - i); if (curAveDou - curAve <= 0.5) { return curAve; } else { return curAve + 1; } } curSum += arr[i]; } return arr[len - 1]; } }
标签:tmp,arr,1300,target,helper,int,res,数组,leetcode 来源: https://www.cnblogs.com/oldby/p/13128540.html