加载中...
1033-移动石子直到连续(Moving Stones Until Consecutive)
发表于:2021-12-03 | 分类: 中等
字数统计: 547 | 阅读时长: 2分钟 | 阅读量:

原文链接: https://leetcode-cn.com/problems/moving-stones-until-consecutive

英文原文

There are three stones in different positions on the X-axis. You are given three integers a, b, and c, the positions of the stones.

In one move, you pick up a stone at an endpoint (i.e., 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, and 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 (i.e., the stones are in three consecutive positions).

Return an integer array answer of length 2 where:

  • answer[0] is the minimum number of moves you can play, and
  • answer[1] is the maximum number of moves you can play.

 

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.

 

Constraints:

  • 1 <= a, b, c <= 100
  • a, b, and c have different values.

中文题目

三枚石子放置在数轴上,位置分别为 abc

每一回合,你可以从两端之一拿起一枚石子(位置最大或最小),并将其放入两端之间的任一空闲位置。形式上,假设这三枚石子当前分别位于位置 x, y, zx < y < z。那么就可以从位置 x 或者是位置 z 拿起一枚石子,并将该石子移动到某一整数位置 k 处,其中 x < k < zk != y

当你无法进行任何移动时,即,这些石子的位置连续时,游戏结束。

要使游戏结束,你可以执行的最小和最大移动次数分别是多少? 以长度为 2 的数组形式返回答案:answer = [minimum_moves, maximum_moves]

 

示例 1:

输入:a = 1, b = 2, c = 5
输出:[1, 2]
解释:将石子从 5 移动到 4 再移动到 3,或者我们可以直接将石子移动到 3。

示例 2:

输入:a = 4, b = 3, c = 2
输出:[0, 0]
解释:我们无法进行任何移动。

 

提示:

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

通过代码

高赞题解

image.png
分情况讨论即可。

class Solution {
public:
    vector<int> numMovesStones(int a, int b, int c) {
        int x=min(min(a,b),c);
        int z=max(max(a,b),c);
        int y=a+b+c-x-z;
        if(y-x==1 && z-y==1) return {0,0};
        if(y-x<=2 || z-y<=2) return {1,z-y+y-x-2};
        else return {2,z-y+y-x-2};
    }
};

统计信息

通过次数 提交次数 AC比率
11246 28643 39.3%

提交历史

提交时间 提交结果 执行时间 内存消耗 语言
上一篇:
1031-两个非重叠子数组的最大和(Maximum Sum of Two Non-Overlapping Subarrays)
下一篇:
1034-边界着色(Coloring A Border)
本文目录
本文目录