Skip to content

Commit 4ecda7a

Browse files
committed
1300
1 parent 33a7f01 commit 4ecda7a

File tree

3 files changed

+41
-0
lines changed

3 files changed

+41
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,7 @@
6161

6262
+ No.50 快速幂 [cpp](cpp/50.cpp) [python](python/50.py)
6363
+ No.128 [cpp](cpp/128.cpp) [python](python/128.py)
64+
+ No.1300 [cpp](cpp/1300.cpp) [python](python/1300.py)
6465

6566
### 剑指offer系列
6667

cpp/1300.cpp

+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
#include <vector>
2+
#include <algorithm>
3+
using namespace std;
4+
5+
class Solution {
6+
public:
7+
int findBestValue(vector<int>& arr, int target) {
8+
sort(arr.begin(), arr.end()); // sort
9+
int l = 0, r = arr.size()-1;
10+
// int pos = (l + r) / 2;
11+
int r_val = arr[r], l_val = arr[l];
12+
int res = (r_val + l_val) / 2, mid = (l+r)/2;
13+
while (l < r) {
14+
/* code */
15+
16+
}
17+
return res;
18+
}
19+
};

python/1300.py

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
class Solution:
2+
def findBestValue(self, arr: List[int], target: int) -> int:
3+
def _sum(arr, m):
4+
__sum = 0
5+
for val in arr:
6+
__sum += val if val <= m else m
7+
return __sum
8+
9+
l, r = 0, max(arr)
10+
while l < r:
11+
mid = (l + r)//2
12+
temp = _sum(arr, mid)
13+
print(l, r, mid, temp)
14+
if temp > target:
15+
r = mid
16+
elif temp < target:
17+
l = mid + 1
18+
else:
19+
return mid
20+
21+
return l-1 if abs(_sum(arr, l) - target) >= abs(_sum(arr, l-1) - target) else l

0 commit comments

Comments
 (0)