Three stones are on a number line at positions a, b, 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 <= a <= 100
1 <= b <= 100
1 <= c <= 100
a != b, b != c, c != a

这题给出三个石头,分别有各自的位置并且不会重叠。要我们求出最小和最大的移动次数,让它们各自紧挨着。

这题好像只要理出几个case就行了。首先假设本身就是紧挨着的,那么肯定最大和最小都是0了。

假设某两个石头之间有1个空位,那么最小的次数肯定是1;假设本身就有两个紧挨着,那么最小次数肯定也是1;其余的case,都是2。

求最大次数的时候,我们只要求出b-a-1和c-b-1的和即可。

class MovingStonesUntilConsecutive : public Solution {
    public:
    void Exec() {

    }
    vector<int> numMovesStones(int a, int b, int c) {
        vector<int> res = {a, b, c};
        std::sort(res.begin(), res.end());
        a = res[0], b = res[1], c = res[2];
        res.clear();

        if (b == a + 1 && c == b + 1) {
            return vector<int>{0, 0};
        }
        if (b == a + 1 || c == b + 1 || b - a == 2 || c - b == 2) {
            res.push_back(1);
        } else {
            res.push_back(2);
        }
        res.push_back(b - a - 1 + c - b - 1);
        return res;
    }
};

共 0 条回复
暂时没有人回复哦,赶紧抢沙发
发表新回复

作者

sryan
today is a good day