移动石子直到连续(贪心)

题目:

image

思路:

这道题是有小技巧的,和一些棋盘题有些类似。利用贪心的极致选择,可以直接把情况划分完。

  • 最少的移动次数:
    • 当三个石子连续放置的时候,最小移动次数为0.
    • 当三个石子中只要有两个石子的距离小于2,即可只需移动另外一个石子1次完成。
    • 其他情况都是最小2次。左右直接贴中间,所以两次。
  • 最多的移动次数:
    • 每次规定只能移动一个格子,即为最多。所以z-x-2次。(其实就是(z-y-1)+(y-x-1))。

代码:

class Solution {
    public int[] numMovesStones(int a, int b, int c) {
        int x = Math.min(Math.min(a, b), c);
        int z = Math.max(Math.max(a, b), c);
        int y = a + b + c - x - z;

        int[] res = new int[2];
        res[0] = 2;
        if (z - y == 1 && y - x == 1) {
            res[0] = 0;
        } else if (z - y <= 2 || y - x <= 2) {
            res[0] = 1;
        }
        res[1] = z - x - 2;
        return res; 
    }
}
posted on 2024-04-19 21:05  一个痴迷于技术的码农  阅读(20)  评论(0)    收藏  举报