当前位置:网站首页>Leetcode:1300. the sum of the array closest to the target value after transforming the array [dichotomy]
Leetcode:1300. the sum of the array closest to the target value after transforming the array [dichotomy]
2022-07-28 11:14:00 【White speed Dragon King's review】

analysis
Given value We can get the current sum
You know , With value An increase in sum Also increased
So with target The distance should be a parabola with the opening upward
In this case , Traverse all possible value value , Just find the first one smaller than the left and right
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
summary
function logn Outer layer on
And the previous outer layer on function logn
A little gap
边栏推荐
- c语言实现float型数据转成BCD数据
- Eslint, eslint Chinese document
- RHEL 6.4 installing SVN and Apache
- Question of hanging the interviewer
- Office2013 input mathematical formula above
- RHEL 6.4 安装svn和apache
- ThinkPad指纹验证在win7无法使用的解决方法
- Learn these analysis methods and models, and no longer have no ideas when encountering problems
- EC20/EC25 4G模块AT指令开发总结
- Use the common union and pointer to test the size end
猜你喜欢

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

DHCP实验演示(Huawei交换机设备配置)

The 10th Landbridge cup embedded electronic provincial competition

读懂这6本书,学习MySQL更轻松

Preliminary understanding of float

PHP发送移动MAS短信乱码的解决方法

Zero code | easily realize data warehouse modeling and build Bi Kanban

Generation and use of Lib library files in keil and IAR

低代码(aPaas)为什么最近又火了?

学会这些分析方法及模型,遇到问题不再没思路
随机推荐
Sword finger offer 30. stack containing min function
keil和IAR中lib库文件的生成和使用
什么是WordPress
Three ways for Cortex-M kernel to manage global interrupts
几个数据库的相关概念
【MySQL从入门到精通】【高级篇】(十)MyISAM的索引方案&&索引的优缺点
I use the applet container to improve the efficiency of mobile R & D by 5 times!
Crm+ zero code: easily realize enterprise informatization
Two dimensional prefix and
Eslint, Eslint中文文档
A solution to the problem that ThinkPad fingerprint verification cannot be used in win7
Why should coding and modulation be carried out before transmission
表格数据处理软件,除了Excel还有什么?
JSON preliminary understanding
BOM部分属性及理解
Understanding of the return value of the structure pointer function passed to the structure pointer
RHEL 6.4 installing SVN and Apache
Question of hanging the interviewer
CTF skill tree - file upload
判断数码管是共阳极还是共阴极