365天挑战LeetCode1000题——Day 041 二分查找完结纪念 + 第 N 个神奇数字 + 在线选举

本文介绍了二分查找算法的完结纪念和第N个神奇数字的代码实现,以及在线选举问题的自解代码。通过实例展示了优化技巧和数据结构在实际问题中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

二分查找完结纪念

在这里插入图片描述

878. 第 N 个神奇数字

在这里插入图片描述

代码实现(部分看题解)

class Solution {
public:
    typedef long long ll;
    // greatest common divisor 最大公约数
    ll gcd(ll a, ll b) {
        return b == 0 ? a : gcd(b, a % b);
    }
    // least common multiple 最小公倍数
    ll lcm(ll a, ll b) {
        return a * b / gcd(a, b);
    }

    int nthMagicalNumber(int n, int a, int b) {
        ll ab = lcm(a, b);
        //本题结果在 [1, 2 * 10^9] 的范围内,优化为 [min({a,b,c}), 2 * 10^9]
        ll l = min(a, b) - 1, r = 4e13 + 1; 
        while (l+1 != r) {
            ll mid = (l + r) >> 1;
            // 容斥原理:计算 cnt 为[1,mid]中的丑数个数
            ll cnt = mid / a + mid / b - mid / ab;
            if (cnt < n) {
                l = mid;
            } else {
                r = mid;
            }
        }
        return r % 1000000007;
    }
};

911. 在线选举

在这里插入图片描述

代码实现(自解)

class TopVotedCandidate {
private:
    vector<int> times;
    map<int, int> query;
public:
    TopVotedCandidate(vector<int>& persons, vector<int>& times) :
    times(times) {
        map<int, int> _map;
        int maxVotes = 0, selectedPerson = 0;
        for (int i = 0; i < times.size(); i++) {
            _map[persons[i]]++;
            for (auto it = _map.begin(); it != _map.end(); it++) {
                if (it->second > maxVotes) {
                    maxVotes = it->second;
                    selectedPerson = it->first;
                }
                
            }
            if (maxVotes == _map[persons[i]]) {
                selectedPerson = persons[i];
            }
            query[times[i]] = selectedPerson;
        }
    }
    
    int q(int t) {
        int l = 0, r = times.size() - 1, m = 0;
        while (l < r) {
            m = (l + r + 1) >> 1;
            if (times[m] <= t) l = m;
            else r = m - 1;
        }
        return query[times[l]];
    }
};

/**
 * Your TopVotedCandidate object will be instantiated and called as such:
 * TopVotedCandidate* obj = new TopVotedCandidate(persons, times);
 * int param_1 = obj->q(t);
 */

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值