zoukankan      html  css  js  c++  java
  • 【leetcode】1300. Sum of Mutated Array Closest to Target

    题目如下:

    Given an integer array arr and a target value target, return the integer value such that when we change all the integers larger than value in the given array to be equal to value, the sum of the array gets as close as possible (in absolute difference) to target.

    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: 5
    

    Example 3:

    Input: arr = [60864,25176,27249,21296,20204], target = 56803
    Output: 11361

    Constraints:

    • 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
  • 相关阅读:
    如何在外部获取当前A标签的ID值
    获取<a>标签值</a>的标签值及更改
    Mysql : Maximum execution time of 30 seconds exceeded
    Ajax+PHP实现的进度条--实例
    HTML控件 隐藏
    Ajax学习--理解 Ajax 及其工作原理
    XMLHttpRequest 对象属性参数参考
    七、smarty--缓存的控制
    六、smarty-缓存控制前的页面静态化原理
    Java 的 List 与 Scala 的 Seq 相互转换
  • 原文地址:https://www.cnblogs.com/seyjs/p/12114155.html
Copyright © 2011-2022 走看看