[1040] LeetCode continuous movement until the stone II

A length of the infinite number of axes, the position of the i-th particle gravel stones [i]. If the location of a stone minimum / maximum, then the endpoint is called stone gravel.

Each turn, you can pick up a stone and move the endpoint to a location unoccupied, so that the stone is no longer an endpoint stone.

It is noteworthy that, if the stones like stones = [1,2,5] In this way, you will not be able to move stones endpoint is located at position 5, because whether it will be moved to any position (such as 0 or 3), the stones are still is the endpoint stones.

When you can not make any movement, that is, the position of these stones in a row, the game ends.

To make the game ends, the minimum and maximum number of moves you can perform are how much? An array of length 2 returns Answer: answer = [minimum_moves, maximum_moves].

Example 1:

输入:[7,4,9]
输出:[1,2]
解释:
我们可以移动一次,4 -> 8,游戏结束。
或者,我们可以移动两次 9 -> 5,4 -> 6,游戏结束。

Example 2:

输入:[6,5,4,3,10]
输出:[2,3]
解释:
我们可以移动 3 -> 8,接着是 10 -> 7,游戏结束。
或者,我们可以移动 3 -> 7, 4 -> 8, 5 -> 9,游戏结束。
注意,我们无法进行 10 -> 2 这样的移动来结束游戏,因为这是不合要求的移动。

Example 3:

输入:[100,101,104,102,103]
输出:[0,0]

prompt:

3 <= stones.length <= 10^4
1 <= stones[i] <= 10^9
stones[i] 的值各不相同。

analysis

Most mobile number:
In [7,4,9] as an example, the number of rows according to the size of the shaft
4, , , 7, _, 9
can now be moved only 4, 9, and the movement position of the boundary can not be analyzed:
1 , to move the furthest (the most left slot), must be moved to a position 5 to 9, since up to 4-7 middle of the gap, the slot 9 is moved past the middle of the most possible number of movable up .
2, the slot 9 is moved to the left, from the gap between the 7-9 will be no effect, because the mobile stones, can not move to the boundary
3, the final movement to complete formation of a continuous string of numbers, means that any gap means that once moved
summary, the largest number of moves: total number of voids -min (void left and right gap)

Code

public int[] numMovesStonesII(int[] stones) {
       Arrays.sort(stones);
        int i = 0, n = stones.length;
        int minnerSpace = Math.min(stones[n - 1] - stones[n - 2] - 1, stones[1] - stones[0] - 1);
        int maxMove = (stones[n - 1] - stones[0] - n + 1) - minnerSpace;
        int minMove = stones.length;
        for (int j = 0; j < n; j++) {
            while (stones[j] - stones[i] + 1 > n)
                i++;
            if (j - i == stones[j] - stones[i] && n - (j - i + 1) == 1)
                minMove = Math.min(2, minMove);
            else
                minMove = Math.min(minMove, n - (j - i + 1));
        }
        return new int[]{minMove, maxMove};
    }
Published 55 original articles · won praise 14 · views 20000 +

Guess you like

Origin blog.csdn.net/qq422243639/article/details/98629945