我最近开始学习编程,刚刚完成了edX课程。我试图解决HackerRank上的this问题,并且在每种情况下都没有时间。我做错了什么?
n,k = input().strip().split(' ')
n,k = [int(n),int(k)]
x = [int(x_temp) for x_temp in input().strip().split(' ')]
x.sort()
def transmitter(aList=[], target=0):
'''
accepts a list of house location, and a target location for the transmitter
returns the optimal number of transmitters required to cover all the houses
'''
List = aList[:]
start = target - k
end = target + k + 1
for i in range(start, end):
if i in List:
List.remove(i)
if not List:
return 1
m = max(List)
for e in List:
if transmitter(List, e) < m:
m = transmitter(List, e)
return 1 + m
m = max(x)
for e in x:
if transmitter(x, e) < m:
m = transmitter(x, e)
print(m)
我对此很陌生。很抱歉犯了任何明显的错误,或者发布此错误,以防这不适合的网站。在这种情况下,如果您可以推荐我可以提出此类问题的网站,那将非常有用。
答案 0 :(得分:1)
我非常确定贪婪算法只在O(N)
时间内最佳地解决了这个问题。不需要任何递归。只需将每个发射器放在尽可能远的地方,而不留下任何未覆盖的房屋。当最后一所房子被遮盖时停下来。
以下是我编写代码的方式:
def hackerland(houses, k): # houses should be sorted list of locations
first = None # location of first uncovered house
last = 0 # last location covered by a previous transmitter
prev = None
count = 0 # transmitters = []
for x in houses:
if first is not None and x > first + k:
first = None
count += 1 # transmitters.append(prev)
last = prev + k
if last is not None and x > last:
last = None
first = x
prev = x
if first is not None:
count += 1 # transmitters.append(prev)
return count # return transmitters
我收录的评论显示了如何轻松修改此代码以返回发送方位置列表,而不仅仅是需要多少代码。
答案 1 :(得分:1)
没有必要采取递归方法。事实上,你可以向前工作,在房屋上进行迭代,当先前放置的发射器没有达到覆盖当前房屋的距离时放置发射器等。
比这复杂一点,但并不多。看到这段代码:
# input
n,k = input().strip().split(' ')
n,k = [int(n),int(k)]
x = [int(x_temp) for x_temp in input().strip().split(' ')]
# eliminate duplicate house x-xoordinates, they don't influence the result
houses = list(set(x))
houses.sort()
# add extreme far dummy house (will make the loop easier)
houses.append(100000)
reachedX = 0 # coordinate until where the previously placed transmitter reaches
unreachedX = -1 # coordinate that the next one needs to cover (to the left)
lastHouseId = -1 # index where previous transmitter was placed
transmitters = [] # coordinates of the placed transmitters
for houseId, houseX in enumerate(houses):
if reachedX > unreachedX: # we might still be in range of last transmitter
if houseX > reachedX: # we just went out of reach
unreachedX = houseX # this house must be covered by next one
elif houseX - k > unreachedX: # transmitter here wouldn't reach far enough back
lastHouseId = houseId - 1 # place it on previous house
reachedX = houses[lastHouseId] + k
transmitters.append(houses[lastHouseId])
print(transmitters)
print(len(transmitters))