置頂

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

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

熱門文章

2026年11月3日 星期二

LeetCode 解題筆記:736. Minimum Moves to Equal Array Elements III

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


LeetCode 題目連結:3736. Minimum Moves to Equal Array Elements III

解題想法


簡單題。題目給一個長度為 $n$ 的陣列 $nums$,每次操作可以將陣列中一個數字加 1,至少要操作幾次才能夠讓陣列中每一項都一樣大?

如果原來的陣列最大值為 $imax$,目標就是把所有的數字都補到 $imax$,因此答案 $$ ans = \sum_{i = 0}^{n-1} (imax - nums[i]) = n \times imax - \sum_{i = 0}^{n-1} nums[i] $$

Python 程式碼


Runtime: 2 ms, beats 43.08%. Memory: 19.21 MB, beats 39.49%.
class Solution:
    def minMoves(self, nums: List[int]) -> int:
        return len(nums) * max(nums) - sum(nums)


Runtime: 1 ms, beats 57.44%. Memory: 19.08 MB, beats 92.56%.
class Solution:
    def minMoves(self, nums: List[int]) -> int:
        imax = max(nums)
        return sum(imax - num for num in nums)


C++ 程式碼


Runtime: 1 ms, beats 27.20%. Memory: 31.46 MB, beats 79.45%.
class Solution {
public:
    int minMoves(vector<int>& nums) {
        return nums.size() * (*max_element(nums.begin(), nums.end())) - accumulate(nums.begin(), nums.end(), 0);
    }
};


Runtime: 0 ms, beats 100.00%. Memory: 31.60 MB, beats 45.60%.
class Solution {
public:
    int minMoves(vector<int>& nums) {
        int imax = *max_element(nums.begin(), nums.end());
        int ans = 0;
        for(int num : nums) {
            ans += imax - num;
        }
        return ans;
    }
};


Runtime: 0 ms, beats 100.00%. Memory: 31.22 MB, beats 98.43%.
class Solution {
public:
    int minMoves(vector<int>& nums) {
        int imax = 0;
        for(int num : nums) {
            imax = max(imax, num);
        }

        int ans = 0;
        for(int num : nums) {
            ans += imax - num;
        }

        return ans;
    }
};


C 語言程式碼


Runtime: 0 ms, beats 100.00%. Memory: 9.74 MB, beats 97.50%.
#define max(a, b) ((a) > (b) ? (a) : (b))

int minMoves(int* nums, int numsSize) {
    int imax = 0;
    for(int i = 0; i < numsSize; i++) {
        imax = max(imax, nums[i]);
    }

    int ans = 0;
    for(int i = 0; i < numsSize; i++) {
        ans += imax - nums[i];
    }

    return ans;
}


沒有留言:

張貼留言