1676. 跳石头

1676. 跳石头

CAT 专属题目
中文English

There are n stones between the starting point and the end point. The distance between the starting point and the ith (i starts from 0) stone is d[i]. And the distance between the starting point and end point is target. From the starting point, we can only jump to the adjacent stone until the end point.

Now you can remove at most m stones. Return the the shortest jump distance** from the starting point to the end point** in each case, , what is the maximum value of the shortest distance values of all moving stones?

样例

样例 1:

输入: n = 5, m = 2, target = 25, d = [2,11,14,17,21]
输出: 4
解释: 移走第一个和第三个石头, 然后跳跃的路径就是:
  1. 0 -> 11  11
  2. 11 -> 17 6
  3. 17 -> 21 4
  4. 21 -> 25 4 

样例 2:

输入: n = 0, m = 0, target = 10, d = []
输出: 10
解释: 起点和终点直接没有石头, 也不需要移走任何石头. 直接从起点跳到终点, 距离为 10.

注意事项

  1. 0 \leq m \leq n \leq 50,0000mn50,000
  2. 1 \leq target \leq 1,000,000,0001target1,000,000,000
  3. 这些石头按与起点距离从小到大的顺序给出, 且不会有两个岩石出现在同一个位置.
输入测试数据 (每行一个参数)如何理解测试数据?

二分答案

class Solution:
    """
    @param n: The total number of stones.
    @param m: The total number of stones you can remove.
    @param target: The distance from the end to the starting point.
    @param d: The array that the distance from the i rock to the starting point is d[i].
    @return: Return the maximum value of the shortest jump distance.
    """
    def getDistance(self, n, m, target, d):
        # Write your code here.
        #求最短跳跃距离的最大值
        #如果大于这个距离的话,就需要移走这个石头,count += 1。符合条件的话,count <= m.
        if not d: return target
        start, end = 0, target - 1 
        
        while start + 1 < end:
            mid = (start + end) // 2 
            
            #如果是符合条件,则往右移动(跳跃距离),取最大
            if self.check(mid, d, m):
                start = mid
            else:
                end = mid
        
        #最终出来的start肯定是符合条件的
        return start
    
    def check(self, distance, d, m):
        count = 0 
        #初始上一个石头为0,如果是两块石头的距离 < distance, 则说明两块石头会跳过头,需要移走一块石头
        last_stone = 0
        
        for i in range(len(d)):
            #距离小于跳跃距离,一跳会跳过头,所有需要移走当前石头,最后一块石头还是上一个石头(最后一块石头指的是当前位置的最后一块石头)
            if (d[i] - last_stone < distance):
                count += 1 
            else:
                #否则的话,最后一块石头是当前石头,不需要移走
                last_stone = d[i]
                
        #判断,如果移走的石头大于m,则不符合条件
        if (count > m):
            return False
        return True           

 

 

posted @ 2020-08-16 23:51  风不再来  阅读(302)  评论(0编辑  收藏  举报