365天挑战LeetCode1000题——Day 026 每日一题 + 二分查找 04


676. 实现一个魔法字典(136)

在这里插入图片描述

代码实现(首刷自解)

class MagicDictionary {
public:
    vector<string> dictionary;
    MagicDictionary() {
        dictionary.clear();
    }
    
    void buildDict(vector<string> dictionary) {
        this->dictionary = dictionary;
    }
    
    bool search(string searchWord) {
        int n = searchWord.size();
        for (string word : dictionary) {
            if (word.size() != n) {
                continue;
            }
            int count = 1;
            bool flag = true;
            for (int i = 0; i < n; i++) {
                if (word[i] != searchWord[i]) count--;
                if (count < 0) {
                    flag = false;
                    break;
                }
            }
            if (flag && !count) return true;
        }
        return false;
    }
};

/**
 * Your MagicDictionary object will be instantiated and called as such:
 * MagicDictionary* obj = new MagicDictionary();
 * obj->buildDict(dictionary);
 * bool param_2 = obj->search(searchWord);
 */

875. 爱吃香蕉的珂珂(138)

在这里插入图片描述

代码实现(首刷自解)

class Solution {
public:
    bool check(vector<int> piles, int m, int h) {
        int times = 0;
        auto it = lower_bound(piles.begin(), piles.end(), m);
        times += it - piles.begin();
        while (it != piles.end()) {
            int tmp = *it;
            times += tmp / m + (tmp % m != 0);
            ++it;
        }
        return times <= h;
    }

    int minEatingSpeed(vector<int>& piles, int h) {
        sort(piles.begin(), piles.end());
        int l = 1, r = piles.back();
        while (l < r) {
            int m = l + r >> 1;
            if (check(piles, m, h)) r = m;
            else l = m + 1;
        }
        return l;
    }
};

1552. 两球之间的磁力(139)

在这里插入图片描述

代码实现(部分看题解)

class Solution {
public:
    int check(vector<int>& position, int m) {
        int pre = position[0];
        int n = position.size();
        int count = 1;
        for (int i = 1; i < n; i++) {
            if (position[i] - pre >= m) {
                count++;
                pre = position[i];
            }
        }
        return count;
    }

    int maxDistance(vector<int>& position, int m) {
        sort(position.begin(), position.end());
        int ans;
        int l = 1, r = position.back() - position[0];
        while (l <= r) {
            int mid = l + r >> 1;
            if (check(position, mid) >= m) {
                l = mid + 1;
                ans = mid;
            }
            else r = mid - 1;
        }
        return ans;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值