当前位置:网站首页>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
略有差距
边栏推荐
- GKConstantNoiseSource
- The blogs of excellent programmers at home and abroad are all here, please check it
- Do you want to enroll in class for advanced soft exam
- platform驱动平台下,关于probe函数中,形参dev的“dev->dev.of_node;”的理解
- Question of hanging the interviewer
- The 10th Landbridge cup embedded electronic provincial competition
- JSON preliminary understanding
- Three ways for Cortex-M kernel to manage global interrupts
- 剑指 Offer 06. 从尾到头打印链表
- GKCheckerboardNoiseSource
猜你喜欢

Sword finger offer 06. print linked list from end to end

10_ UE4 advanced_ Add fall and cast actions

盘点:令人心动的数据可视化图表

哈希表的相关知识点

6. MapReduce custom partition implementation

剑指 Offer 06. 从尾到头打印链表

Table data processing software, what else besides excel?

Crm+ zero code: easily realize enterprise informatization

GKVoronoiNoiseSource

ctf技能树----文件上传
随机推荐
ICML 2022 | graph represents the structure aware transformer model of learning
Learn these analysis methods and models, and no longer have no ideas when encountering problems
2021-03-24
1. Sum of two numbers
构建快捷开发IDE:VisualSVN+Sublime+Visual Studio 2013+QuickEasyFTPServer
c语言实现float型数据转成BCD数据
JS - modify the key name of the object in the array
Learn how to do e-commerce data analysis (with operation analysis index framework)
Arduino基础知识
Nodejs: set up the express service, set up the session and realize the exit operation
Install GMP
5. Implement MapReduce program on window side to complete wordcount function
Tree Shaking和DCE
Inventory: 144 free learning websites, the most complete collection of resources in the whole network
蓝桥杯嵌入式-HAL库-ADC
JSON preliminary understanding
盘点:令人心动的数据可视化图表
Relevant knowledge points of hash table
Sword finger offer 35. replication of complex linked list
蓝桥杯嵌入式-HAL库-USART_TX