HackerRank做题

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())
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值