当前位置:网站首页>leetcode:1300. 转变数组后最接近目标值的数组和【二分】
leetcode:1300. 转变数组后最接近目标值的数组和【二分】
2022-07-28 10:44:00 【白速龙王的回眸】

分析
给定value我们可以得到当前的sum
可知,随着value的增加sum也是增加的
因此和target的距离应该是开口朝上的抛物线
这样的话,遍历所有可能的value值,找到第一个小于左右两边的即可
Ac code
class Solution:
def findBestValue(self, arr: List[int], target: int) -> int:
n = len(arr)
arr.sort()
preSum = list(accumulate(arr))
# logn
def get_diff(value):
idx = bisect_right(arr, value)
# avoid 0 - 1 = -1
if idx == 0:
nowSum = n * value
else:
nowSum = preSum[idx - 1] + value * (n - idx)
#print(preSum[idx - 1], value, n - idx)
return abs(nowSum - target)
minn, maxn = 0, arr[-1]
for ans in range(minn, maxn + 1):
#print(ans)
#print(get_diff(ans - 1), get_diff(ans), get_diff(ans + 1))
if get_diff(ans - 1) >= get_diff(ans) <= get_diff(ans + 1):
return ans
总结
函数logn 外层on
和以前的外层on 函数logn
略有差距
边栏推荐
- 吊打面试官的问题
- EC20/EC25 4G模块AT指令开发总结
- Usage of memory operation functions memcpy() and memmove()
- 02.1.2. logic type bool
- Learn these analysis methods and models, and no longer have no ideas when encountering problems
- 一文学会如何做电商数据分析(附运营分析指标框架)
- 剑指 Offer 35. 复杂链表的复制
- MySQL Architecture Principle
- If you don't climb mountains, you don't know the height of the sky; If you don't face deep streams, you don't know the thickness of the earth
- I don't know how lucky the boy who randomly typed logs is. There must be a lot of overtime
猜你喜欢

Product side data analysis thinking

Relevant knowledge points of hash table

BC35 NB模块AT指令开发总结

Sword finger offer 30. stack containing min function

Installation points and precautions of split angle probe

Make a virtual human with zego avatar | virtual anchor live broadcast solution

蓝桥杯嵌入式-HAL库-USART_TX

Advance.ai sailing guide helps enterprises sail to Indonesia and grasp half of the Southeast Asian market

I use the applet container to improve the efficiency of mobile R & D by 5 times!

keil和IAR中lib库文件的生成和使用
随机推荐
Samba learning
Causes and solutions of invalid ROM table
GKARC4RandomSource
Development environment configuration of nodemcu
The 10th Landbridge cup embedded electronic provincial competition
ThinkPad指纹验证在win7无法使用的解决方法
Tree Shaking和DCE
盘点:6本书教会你职场晋升必备技能
数组相关的知识点
Eslint, eslint Chinese document
读懂这6本书,学习MySQL更轻松
栈和队列
EC20/EC25 4G模块AT指令开发总结
Using k-means clustering to classify tariff models of different industries
The solution of PHP sending mobile MAS SMS garbled code
理解Oracle的几个概念
哈希表的相关知识点
Jianzhi offer 09. realize queue with two stacks
Redis-day01 common sense supplement and redis introduction
float浮动初步理解