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

文章目录

  • 676. 实现一个魔法字典(136)
    • 代码实现(首刷自解)
  • 875. 爱吃香蕉的珂珂(138)
    • 代码实现(首刷自解)
  • 1552. 两球之间的磁力(139)
    • 代码实现(部分看题解)


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

365天挑战LeetCode1000题——Day 026 每日一题 + 二分查找 04_第1张图片

代码实现(首刷自解)

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)

365天挑战LeetCode1000题——Day 026 每日一题 + 二分查找 04_第2张图片

代码实现(首刷自解)

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)

365天挑战LeetCode1000题——Day 026 每日一题 + 二分查找 04_第3张图片

代码实现(部分看题解)

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;
    }
};

你可能感兴趣的:(LeetCode千题之路,算法,leetcode,数据结构)