题目如下:

Three stones are on a number line at positions ab, and c.

Each turn, you pick up a stone at an endpoint (ie., either the lowest or highest position stone), and move it to an unoccupied position between those endpoints.  Formally, let's say the stones are currently at positions x, y, z with x < y < z.  You pick up the stone at either position x or position z, and move that stone to an integer position k, with x < k < z and k != y.

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: a = 1, b = 2, c = 5
Output: [1,2]
Explanation: Move the stone from 5 to 3, or move the stone from 5 to 4 to 3.

Example 2:

Input: a = 4, b = 3, c = 2
Output: [0,0]
Explanation: We cannot make any moves.

Example 3:

Input: a = 3, b = 5, c = 1
Output: [1,2]
Explanation: Move the stone from 1 to 4; or move the stone from 1 to 2 to 4.

Note:

  1. 1 <= a <= 100
  2. 1 <= b <= 100
  3. 1 <= c <= 100
  4. a != b, b != c, c != a

解题思路:首先对a,b,c进行排序,使得a最小,b其次,c最大。最大的移动次数很好求,就是a与c分别往b移动,每次移动一步,很容易得到最大移动次数是abs(c-b-1) + abs(b-a-1)。最小移动次数似乎很直接,就是a与c直接一步移动到b的两侧,这种情况下值应该是2,但是有几种特殊场景:第一是a,b,c都相邻,那么值是0;第二种是a与b相邻或者b与c相邻,那么值为1;第三种是a与b的差值为2或者b与c的差值位2,这时可以直接那剩余那个元素一步移动到a与b或者b与c的直接的空位中。

代码如下:

class Solution(object):
def numMovesStones(self, a, b, c):
"""
:type a: int
:type b: int
:type c: int
:rtype: List[int]
"""
l = sorted([a,b,c])
a,b,c = l[0],l[1],l[2]
maxv = abs(c-b-1) + abs(b-a-1)
minv = 0
left = (b-a-1)
right = (c-b-1)
if left == 0 and right == 0:
minv = 0
elif left == 0 or right == 0:
minv = 1
elif left == 1 or right == 1:
minv = 1
else:
minv = 2
return [minv,maxv]

最新文章

  1. 机器学习实战笔记(Python实现)-04-Logistic回归
  2. MMORPG大型游戏设计与开发(服务器 游戏场景 掉落与网络连接)
  3. PHP中如何在数组中随机抽取n个数据的值 - array_rand()?
  4. Leetcode: Valid Word Square
  5. 基于webpack的前端工程化开发解决方案探索(一):动态生成HTML(转)
  6. iOS10新特性之CallKit开发详解:锁屏接听和来电识别
  7. python 可变参数
  8. MSDN上面测试Window的方法(很好用)
  9. 【BZOJ 1191】 [Apio2010]特别行动队 (斜率优化)
  10. Caused by: java.lang.ClassNotFoundException: org.dom4j.DocumentException
  11. CodeForces 659F Polycarp and Hay
  12. java工程开发之图形化界面之(第四课)
  13. Swift 项目中常用的第三方框架
  14. Leetcode_128_Longest Consecutive Sequence
  15. JQuery实现省市区的三级联动
  16. mongo 复制集命令
  17. Python中的pass的作用
  18. synchronized和lock
  19. Nosql数据库的四大分类及分布式数据库CAP原理
  20. springmvc-自定义消息转换器

热门文章

  1. springMVC解决跨域
  2. 阶段1 语言基础+高级_1-3-Java语言高级_08-JDK8新特性_第3节 两种获取Stream流的方式_11_练习:集合元素处理(Stream方式)
  3. delphi 静态3维数组。 严重占用堆栈 切记。 应该用动态数组, 非要用静态数组的话, 要在编译器里 把 堆栈 调大
  4. 解决旋转屏幕闪退在androidManifest.template.xml里,activity项添加:
  5. 前端框架React入门课程【视频】
  6. CEPH安装(CentOS 7)
  7. tbox新增stackless协程支持
  8. 初学Java总结
  9. P3188 [HNOI2007]梦幻岛宝珠
  10. .NET的优点(转载)