原题链接
题干
给定三个石子a,b,c,假定a<b<c,则称a为左端点,b为中间点,c为右端点。现按照一下规则移动石子:
每次移动两个端点之一的石子,将其移动到两端点之间且不与中间点重合的任意一个位置。
现想通过移动,使三个石子连续,问:最多需要移动多少次,最少需要移动多少次。
思路
首先将三个石子从小到大排序。
对于最少移动次数,主要有三种情况:
0次:三个石子已经连续
1次:(1)有两个石子连续,此时只需将另一石子移动到中间点前或后即可;
(2)有两个石子之间距离为2,此时只需将另一石子移至这两个石子中间即可;
2次:以上情况均不成立,此时需要将左右端点没别移至中间点前后。
对于最多移动次数,只需将左右端点徐徐(一次移一步)地移到中间点的前后。
代码
class Solution {
public:
vector<int> numMovesStones(int a, int b, int c) {
if(a > b) swap(a, b);
if(a > c) swap(a, c);
if(b > c) swap(b, c);
int min_moves=-1, max_moves=-1;
if(a == b-1 && b == c-1){
min_moves = 0;
}else if(a == b-1 || b == c-1 || b-a==2 || c-b==2){
min_moves = 1;
}else{
min_moves = 2;
}
max_moves = b-a + c-b -2;
return {min_moves, max_moves};
}
};