1 class Solution: 2 def findBestValue(self, arr: 'List[int]', target: int) -> int: 3 l, r = 0, 10**5 4 diff = abs(sum(arr) - target) 5 res = collections.defaultdict(list) 6 while l < r: 7 m = (l + r) // 2 8 s = sum([m if n > m else n for n in arr]) 9 if abs(s - target) <= diff: 10 diff = abs(s - target) 11 res[diff] += [m] 12 if s < target: 13 l = m + 1 14 else: 15 r = m 16 return min(res[diff])
补充另一个,使用Java实现的代码,可读性好一些:
1 class Solution { 2 public int findBestValue(int[] arr, int target) { 3 int left = 1; 4 int right = target; 5 6 int diff = 0; 7 while (left < right) { 8 int mid = left + (right - left) / 2; 9 int sum = calSum(arr, mid); 10 diff = sum - target; 11 if (diff == 0) { 12 return mid; 13 } else if (diff < 0) { 14 left = mid + 1; 15 } else if (diff > 0) { 16 right = mid; 17 } 18 } 19 20 diff = calSum(arr, left) - target; 21 int prevDiff = calSum(arr, left - 1) - target; 22 23 // System.out.println("now left " + left + " diff " + diff); 24 // System.out.println("Math.abs(prevDiff)" + Math.abs(prevDiff) + 25 // " Math.abs(diff)" + Math.abs(diff)); 26 27 return Math.abs(prevDiff) <= Math.abs(diff) ? left - 1 : left; 28 } 29 30 int calSum(int[] arr, int val) { 31 int sum = 0; 32 for (int i = 0; i < arr.length; i++) { 33 if (arr[i] > val) { 34 sum += val; 35 } else { 36 sum += arr[i]; 37 } 38 } 39 40 return sum; 41 } 42 }
算法思路:二分查找。