iT邦幫忙

2025 iThome 鐵人賽

DAY 25
0

https://ithelp.ithome.com.tw/upload/images/20251008/20177944lEqQl27ss2.jpg

https://ithelp.ithome.com.tw/upload/images/20251008/20177944yGFKdoaykN.jpg

範例追蹤(a = [4,5,6,7,0,1,2], t = 0):
初始 l=0 r=6 m=3 a[m]=7。a[l]<=a[m] 成立,0 不在 [4,7),所以 l=4。
現在 l=4 r=6 m=5 a[m]=1。左半有序,0 在 [0,1),所以 r=4。
現在 l=4 r=4 m=4 a[m]=0,找到回傳 4。

#include <vector>
using namespace std;

class Solution {
public:
    int search(const vector<int>& a, int t) const {
        if (a.empty()) return -1;
        int l = 0;
        int r = static_cast<int>(a.size()) - 1;
        while (l <= r) {
            int m = l + ((r - l) >> 1);
            if (a[m] == t) return m;
            if (a[l] <= a[m]) {
                if (a[l] <= t && t < a[m]) r = m - 1;
                else l = m + 1;
            } else {
                if (a[m] < t && t <= a[r]) l = m + 1;
                else r = m - 1;
            }
        }
        return -1;
    }
};

有推薦筆電嗎 之前在巴塞隆納被整包偷走都是借用筆電嗚嗚


上一篇
I have memorized it 34 & 原來有Badge嚇到XD SOLVING PROBLEMS 50+ DAYS
系列文
轉職仔之Data Science and ai master後的持續精進技術之路25
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言