标签:arr 1300 Target Closest value amount inx Example target
题目如下:
Given an integer array
arr
and a target valuetarget
, return the integervalue
such that when we change all the integers larger thanvalue
in the given array to be equal tovalue
, the sum of the array gets as close as possible (in absolute difference) totarget
.In case of a tie, return the minimum such integer.
Notice that the answer is not neccesarilly a number from
arr
.Example 1:
Input: arr = [4,9,3], target = 10 Output: 3 Explanation: When using 3 arr converts to [3, 3, 3] which sums 9 and that's the optimal answer.Example 2:
Input: arr = [2,3,5], target = 10 Output: 5Example 3:
Input: arr = [60864,25176,27249,21296,20204], target = 56803 Output: 11361Constraints:
1 <= arr.length <= 10^4
1 <= arr[i], target <= 10^5
解题思路:首先对arr进行排序。如果要把数组中所有大于value的数替换成value,那么可以通过二分查找的方法找出value在arr中出现的位置,左半部分的元素不需要改变,直接求和,右半部分的元素的和为 length * value。
代码如下:
class Solution(object): def findBestValue(self, arr, target): """ :type arr: List[int] :type target: int :rtype: int """ import bisect diff = float('inf') res = 0 arr.sort() val = [] count = 0 for i in arr: count += i val.append(count) for v in range(0,arr[-1] + 1): inx = bisect.bisect_right(arr,v) amount = v * (len(arr) - inx) if inx > 0:amount += val[inx-1] if diff > abs(amount - target): diff = abs(amount - target) res = v return res
标签:arr,1300,Target,Closest,value,amount,inx,Example,target 来源: https://www.cnblogs.com/seyjs/p/12114155.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。