置頂

我的 VPython 教學文件 (HackMD 版本)

VPython 教學文件目錄 安裝及測試 基本語法 等速度直線運動 自由落下 終端速度 水平抛射 使用For迴圈計算水平抛射資料 斜向抛射 圓周運動 簡諧運動 單擺 木塊彈簧系統分離 重力及簡諧 行星運動 相疊木塊 雙重簡諧運動 一維彈性碰撞 ...

熱門文章

2026年11月26日 星期四

LeetCode 解題筆記:3360. Stone Removal Game

作者:王一哲
日期:2026年11月26日


LeetCode 題目連結:3360. Stone Removal Game

解題想法


簡單題。題目給一個整數 $n ~(1 \leq n \leq 50)$,代表遊戲一開始的石頭數量。遊戲固定由 Alice 先行動。第一回合行動的人要移除 $10$ 個石頭,第二回行動的人要移除 $9$ 個石頭,第三回行動的人要移除 $8$ 個石頭,其餘依此類推。如果這回合行動的人無法移除指定數量的石頭,則這個人輸掉這場遊戲。如果 Alice 獲勝回傳 True,反之回傳 False。

因為 $n$ 很小,可以用一個 while 迴圈模擬遊戲的過程,速度很快。也可以直接推出 Alice 落敗的條件為 $1 \leq n < 10, 19 \leq n < 20, 34 \leq n < 40, 45 \leq n < 49$。

Python 程式碼


Runtime: 0 ms, beats 100.00%. Memory: 19.08 MB, beats 85.58%.
class Solution:
    def canAliceWin(self, n: int) -> bool:
        flag = False
        x = 10
        while n >= x:
            n -= x
            x -= 1
            flag = not flag
        return flag


Runtime: 0 ms, beats 100.00%. Memory: 19.13 MB, beats 59.13%.
class Solution:
    def canAliceWin(self, n: int) -> bool:
        if 1 <= n < 10 or 19 <= n < 27 or 34 <= n < 40 or 45 <= n < 49:
            return False
        
        return True


C++ 程式碼


Runtime: 0 ms, beats 100.00%. Memory: 7.82 MB, beats 11.49%.
class Solution {
public:
    bool canAliceWin(int n) {
        bool flag = false;
        int x = 10;
        while(n >= x) {
            n -= x;
            x--;
            flag = !flag;
        }
        return flag;
    }
};


Runtime: 0 ms, beats 100.00%. Memory: 7.80 MB, beats 11.49%.
class Solution {
public:
    bool canAliceWin(int n) {
        if ((n >= 1 && n < 10) || (n >= 19 && n < 27) ||
            (n >= 34 && n < 40) || (n >= 45 && n < 49)) {
            return false;
        }
        return true;
    }
};


C 語言程式碼


Runtime: 0 ms, beats 100.00%. Memory: 8.33 MB, beats 66.67%.
bool canAliceWin(int n) {
    bool flag = false;  // Alice 是否獲勝
    int x = 10;  // 這回合要移除的量
    while(n >= x) {
        n -= x;
        x--;
        flag = !flag;
    }
    return flag;
}


Runtime: 0 ms, beats 100.00%. Memory: 8.28 MB, beats 95.83%.
bool canAliceWin(int n) {
    if ((n >= 1 && n < 10) || (n >= 19 && n < 27) ||
        (n >= 34 && n < 40) || (n >= 45 && n < 49)) {
        return false;
    }
    return true;
}


沒有留言:

張貼留言