置頂

GeoGebra 文章目錄

GeoGebra 文章目錄  更新日期:2018/2/8 我將 GeoGebra 相關的文章及檔案連結都整理在這篇裡,之後如果有新的文章也會同時更新這個目錄。上傳到 GeoGebraTube 的檔案,我有試著用 Google Chrome 63.0.3239.13...

熱門文章

2026年6月4日 星期四

LeetCode 解題筆記:3751. Total Waviness of Numbers in Range I

作者:王一哲
日期:2026年6月4日


LeetCode 題目連結:3751. Total Waviness of Numbers in Range I

解題想法


題目要計算指定閉區間 $[num1, num2]$ 之間的數字有幾個山峰或山谷,山峰是指兩側的數字皆小於中間的數字,山谷是指兩側的數字皆大於中間的數字。這題最直接的想法,是用一個 for 迴圈掃過 $[num1, num2]$ 之間所有的數字 $i$,再將 $i$ 轉成字串 $s$。假設字串長度為 $n$,用一個 for 迴圈從索引值 $j = 1$ 檢查到索引值 $j = n-2$,如果 $s[j] > s[j-1] ~\text{and}~ s[j] > s[j+1]$ 或 $s[j] < s[j-1] ~\text{and}~ s[j] < s[j+1]$,就將答案加1。 我本來還在想應該有更好的解法,沒想到底下的提示直接寫 Use bruteforce,而且這個暴力解的速度還不慢,就暫時先這樣寫了。

Python 程式碼


Runtime: 235 ms, beats 90.42%. Memory: 19.27 MB, beats 69.73%.
class Solution:
    def totalWaviness(self, num1: int, num2: int) -> int:
        cnt = 0
        for i in range(num1, num2 + 1):
            s = str(i)
            n = len(s)
            for j in range(1, n-1):
                if (s[j] > s[j-1] and s[j] > s[j+1]) or \
                   (s[j] < s[j-1] and s[j] < s[j+1]):
                    cnt += 1
        return cnt


C++ 程式碼


Runtime: 43 ms, beats 76.87%. Memory: 9.44 MB, beats 59.70%.
class Solution {
public:
    int totalWaviness(int num1, int num2) {
        int cnt = 0;
        for(int i = num1; i <= num2; i++) {
            string s = to_string(i);
            int n = (int)s.size();
            for(int j = 1; j < n-1; j++) {
                if ((s[j] > s[j-1] && s[j] > s[j+1]) ||
                    (s[j] < s[j-1] && s[j] < s[j+1])) {
                    cnt++;
                }
            }
        }
        return cnt;
    }
};


沒有留言:

張貼留言