leetcode1300

Posted AsenYang

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode1300相关的知识,希望对你有一定的参考价值。

 1 class Solution:
 2     def findBestValue(self, arr: List[int], target: int) -> int:
 3         l, r = 0, 10**5
 4         diff = abs(sum(arr) - target)
 5         res = collections.defaultdict(list)
 6         while l < r:
 7             m = (l + r) // 2
 8             s = sum([m if n > m else n for n in arr])
 9             if abs(s - target) <= diff:
10                 diff = abs(s - target)
11                 res[diff] += [m]
12             if s < target:
13                 l = m + 1
14             else: 
15                 r = m
16         return min(res[diff])

参考:https://leetcode.com/problems/sum-of-mutated-array-closest-to-target/discuss/464211/Python-Binary-Search

 

补充另一个,使用Java实现的代码,可读性好一些:

 1 class Solution {
 2     public int findBestValue(int[] arr, int target) {
 3         int left = 1;
 4         int right = target;
 5         
 6         int diff = 0;
 7         while (left < right) {
 8             int mid = left + (right - left) / 2;
 9             int sum = calSum(arr, mid);
10             diff = sum - target;
11             if (diff == 0) {
12                 return mid;
13             } else if (diff < 0) {
14                 left = mid + 1;
15             } else if (diff > 0) {
16                 right = mid;
17             }
18         }
19         
20         diff = calSum(arr, left) - target;
21         int prevDiff = calSum(arr, left - 1) - target;
22         
23         // System.out.println("now left " + left + " diff " + diff);
24         // System.out.println("Math.abs(prevDiff)" + Math.abs(prevDiff) + 
25         //                    " Math.abs(diff)" + Math.abs(diff));
26         
27         return Math.abs(prevDiff) <= Math.abs(diff) ? left - 1 : left;
28     }
29     
30     int calSum(int[] arr, int val) {
31         int sum = 0;
32         for (int i = 0; i < arr.length; i++) {
33             if (arr[i] > val) {
34                 sum += val;
35             } else {
36                 sum += arr[i];
37             }
38         }
39         
40         return sum;
41     }
42 }

参考:https://leetcode.com/problems/sum-of-mutated-array-closest-to-target/discuss/464132/Java-3ms-binary-search-clean-readable-code

算法思路:二分查找。

以上是关于leetcode1300的主要内容,如果未能解决你的问题,请参考以下文章

leetcode1300. Sum of Mutated Array Closest to Target

如何将回收器视图添加到片段

Leetcode 1300. Sum of Mutated Array Closest to Target

leetcode_1292. Maximum Side Length of a Square with Sum Less than or Equal to Threshold_[二维前缀和](代码片段

片段布局为空白

链接到查看内部片段