Climbing the Leaderboard
链接
https://www.hackerrank.com/challenges/climbing-the-leaderboard/problem
思路
此处两边同时遍历即可,代价是O(n)
知识回顾
python的列表切片后不能赋值:nums[i:] = 1是不可以的
代码
def climbingLeaderboard(scores, alice):
new_scores = list(set(scores))
new_scores.sort(reverse = True)
# remove duplicate and remain order
index = len(new_scores) - 1
for i in range(len(alice)):
while alice[i] >= new_scores[index]:
index -= 1
if index < 0:
for j in range(i, len(alice)):
alice[j] = 1
break
if index < 0:
break
alice[i] = index + 2
return alice
Queen’s Attack II
链接
https://www.hackerrank.com/challenges/queens-attack-2/problem
思路
用字典来做这种题,每个方向存放该方向能放置的最大棋子个数。
代码
def queensAttack(self,n, k, r_q, c_q, obstacles):
def check(x, indicator):
if indicator == -1:
return x-1
elif indicator == 0:
return n
else:
return n - x
def sign(x):
if x > 0:
return 1
elif x == 0:
return 0
else:
return -1
position_dict = {0:[1,0],1:[-1,0],2:[1,1],3:[1,-1],4:[0,1],5:[0,-1],6:[-1,1],7:[-1,-1]}
obstacles_dict = {}
for i in position_dict.values():
obstacles_dict["%d%d"%(i[0], i[1])] = min(check(r_q,i[0]), check(c_q,i[1]))
for i in range(k):
r, c = obstacles[i][0] - r_q, obstacles[i][1] - c_q
if abs(r)==abs(c) or r*c == 0:
key = "%d%d"%(sign(r), sign(c))
length = max(abs(r),abs(c)) - 1
if obstacles_dict[key] > length:
obstacles_dict[key] = length
print(obstacles_dict)
return sum(obstacles_dict.values())