Skip to content
Projects
Groups
Snippets
Help
This project
Loading...
Sign in / Register
Toggle navigation
6
6_homework_yangpeng
Overview
Overview
Details
Activity
Cycle Analytics
Repository
Repository
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Issues
0
Issues
0
List
Board
Labels
Milestones
Merge Requests
0
Merge Requests
0
CI / CD
CI / CD
Pipelines
Jobs
Schedules
Charts
Wiki
Wiki
Snippets
Snippets
Members
Collapse sidebar
Close sidebar
Activity
Graph
Charts
Create a new issue
Jobs
Commits
Issue Boards
Open sidebar
杨鹏
6_homework_yangpeng
Commits
01a25b1c
Commit
01a25b1c
authored
Jan 18, 2019
by
yangpengflag
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
Initial commit
parents
Hide whitespace changes
Inline
Side-by-side
Showing
2 changed files
with
55 additions
and
0 deletions
+55
-0
Solution.py
+55
-0
__init__.py
+0
-0
No files found.
Solution.py
0 → 100644
View file @
01a25b1c
import
bisect
class
Solution
(
object
):
def
findRadius
(
self
,
houses
,
heaters
):
"""
冬季已经来临。 你的任务是设计一个有固定加热半径的供暖器向所有房屋供暖。
现在,给出位于一条水平线上的房屋和供暖器的位置,找到可以覆盖所有房屋的最小加热半径。
所以,你的输入将会是房屋和供暖器的位置。你将输出供暖器的最小加热半径。
说明:
给出的房屋和供暖器的数目是非负数且不会超过 25000。
给出的房屋和供暖器的位置均是非负数且不会超过10^9。
只要房屋位于供暖器的半径内(包括在边缘上),它就可以得到供暖。
所有供暖器都遵循你的半径标准,加热的半径也一样。
:type houses: List[int]
:type heaters: List[int]
:rtype: int
"""
# 遍历房子,找到每个房子在加热器中的位置(排序好的加热器)算出距离该房子最近的左右两端加热器离房子的距离并取最小值。最后取出这些最小值中的最大值。边界加判断条件。
# 若没找到待查元素,返回该元素应该存在的第x位置的负值。
# Python: bisect.bisect_left:若找到待查元素,返回元素索引;
# 若没找到待查元素,返回该元素应该存在的位置的索引。
list
.
sort
(
heaters
)
res
=
0
# 半径
disleft
=
0
# 每个房子离左边最近一个加热器的距离
disright
=
0
# 每个房子离右边最近一个加热器的距离
for
house
in
houses
:
index
=
bisect
.
bisect_left
(
heaters
,
house
)
#使用二分法获得房子在加热器中的位置,返回的是索引
print
(
"房子
%
s在加热器中的位置:
%
s"
%
(
house
,
index
))
disleft
=
house
-
heaters
[
index
-
1
]
if
index
-
1
>=
0
else
float
(
'inf'
)
#计算当前房子在取暖器中与前面最近一个取暖器的距离,当房子是第一个时,返回正无穷大
disright
=
heaters
[
index
]
-
house
if
index
<
len
(
heaters
)
else
float
(
'inf'
)
#计算当前房子在取暖器中与后面最近一个取暖器的距离,当房子就是最后一个时取正无穷大
res
=
max
(
res
,
min
(
disleft
,
disright
))
#获取当前房子与左右2个取暖器位置距离的最小值,与其他房子在取暖器中的距离最小值比较,取最大的距离即可覆盖所有距离半径
print
(
res
)
return
res
if
__name__
==
"__main__"
:
solution
=
Solution
()
# houses,heaters = [1,2,3,4],[1,4]
# solution.findRadius(houses,heaters)
houses
,
heaters
=
[
1
,
3
,
5
,
9
],[
1
,
4
]
solution
.
findRadius
(
houses
,
heaters
)
\ No newline at end of file
__init__.py
0 → 100644
View file @
01a25b1c
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment