编程语言
首页 > 编程语言> > LeetCode题解(1300):转变数组后最接近目标值的数组和(Python)

LeetCode题解(1300):转变数组后最接近目标值的数组和(Python)

作者:互联网

题目:原题链接(中等)

标签:二分查找、数组

解法时间复杂度空间复杂度执行用时
Ans 1 (Python) O ( N l o g T ) O(NlogT) O(NlogT) O ( 1 ) O(1) O(1)88ms (35.75%)
Ans 2 (Python)
Ans 3 (Python)

解法一:

class Solution:
    def findBestValue(self, arr: List[int], target: int) -> int:
        left, right = 0, max(arr)

        while left < right:
            mid = (left + right) // 2

            res = sum([n if n <= mid else mid for n in arr])

            if res < target:
                left = mid + 1
            elif res > target:
                right = mid
            else:
                return mid

        res1 = sum([n if n <= (left - 1) else (left - 1) for n in arr])
        res2 = sum([n if n <= left else left for n in arr])

        if abs(res1 - target) > abs(res2 - target):
            return left
        else:
            return left - 1

标签:right,1300,Python,题解,mid,int,数组,return,left
来源: https://blog.csdn.net/Changxing_J/article/details/112858219