[leetcode] 1040. Moving Stones Until Consecutive II

Description

On an infinite number line, the position of the i-th stone is given by stones[i]. Call a stone an endpoint stone if it has the smallest or largest position.

Each turn, you pick up an endpoint stone and move it to an unoccupied position so that it is no longer an endpoint stone.

In particular, if the stones are at say, stones = [1,2,5], you cannot move the endpoint stone at position 5, since moving it to any position (such as 0, or 3) will still keep that stone as an endpoint stone.

The game ends when you cannot make any more moves, ie. the stones are in consecutive positions.

When the game ends, what is the minimum and maximum number of moves that you could have made? Return the answer as an length 2 array: answer = [minimum_moves, maximum_moves]

Example 1:

Input: [7,4,9]
Output: [1,2]
Explanation: 
We can move 4 -> 8 for one move to finish the game.
Or, we can move 9 -> 5, 4 -> 6 for two moves to finish the game.

Example 2:

Input: [6,5,4,3,10]
Output: [2,3]
We can move 3 -> 8 then 10 -> 7 to finish the game.
Or, we can move 3 -> 7, 4 -> 8, 5 -> 9 to finish the game.
Notice we cannot move 10 -> 2 to finish the game, because that would be an illegal move.

Example 3:

Input: [100,101,104,102,103]
Output: [0,0]

Note:

  1. 3 <= stones.length <= 10^4.
  2. 1 <= stones[i] <= 10^9.
  3. stones[i] have distinct values

分析

题目的意思是:给定一个数组,问把数组变成连续递增的数组需要把数组里面的数组变换多少次,求最少的次数和最多的次数。
这道题已经超越了我的知识局限性了,我也做不出来,看了一个比较好的参考答案,首先对stones进行排序,然后遍历求出两数之差大于等于n的次数,至于后面的公式为啥是这样,我也不太清楚,可能是发现了什么规律吧,如果有人知道,可以跟我讨论一下哈

代码

class Solution:
    def numMovesStonesII(self, stones: List[int]) -> List[int]:
        stones.sort()
        n=len(stones)
        i=0
        for j in range(n):
            if(stones[j]-stones[i]>=n):
                i+=1
        if(i==1 and stones[-1]-stones[0]!=n and (stones[-2]-stones[0]==n-2 or stones[-1]-stones[1]==n-2)):
            left=2
        else:
            left=i
        right=stones[-1]-stones[0]-n-min(stones[1]-stones[0],stones[-1]-stones[-2])+2
        return [left,right]

参考文献

[LeetCode] python 100%

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值