leetcode 3433

3433: 统计用户被提及情况

思路:排序+模拟

注意输入的 events 不保证是按时间顺序发生的,需要先排序。

按照时间戳 timestamp 从小到大排序,时间戳相同的,离线事件排在前面,因为题目要求「++状态变更++在所有相同时间发生的消息事件之前处理」。

然后模拟:

  • 离线事件:用一个数组 onlineT 记录用户下次在线的时间戳(60 秒后)。如果当前时间戳>= onlineT[i],则表示用户 i 已在线。

  • 消息事件:把相应用户的提及次数加一。

    string& mention = e[2];

复制代码
else{ // @id
    int idx=0;
    for(int i=0;i<mention.size();i++){
        if(isdigit(mention[i])) idx=idx*10+(mention[i]-'0');
        if(i+1==mention.size() || mention[i+1]==' '){
            ans[idx]++;
            idx=0;
        }
    }
}
  • isdigit(mention[i]) 是判断字符串 mentioni 个字符是不是 十进制数字字符'0'--'9'

  • 1 <= numberOfUsers <= 100 因此要考虑可能出现形似id12 的情况idx=idx*10+(mention[i]-'0')

    class Solution {
    public:
    vector<int> countMentions(int numberOfUsers, vector<vector<string>>& events) {
    vector<int> ans(numberOfUsers);
    vector<int> online_t(numberOfUsers,0);
    // 按照时间戳从小到大排序,时间戳相同的,离线事件排在前面
    //两两比较,["MESSAGE","10","id1 id0"],["OFFLINE","11","0"]
    auto cmp=[](const vector<string>& lth,const vector<string>& rth){
    int lth_tsp=stoi(lth[1]); //stoi适用于string转int
    int rth_tsp=stoi(rth[1]);
    if(lth_tsp!=rth_tsp) return lth_tsp<rth_tsp;
    else return lth[0]>rth[0]; // "OFFLINE" > "MESSAGE" 字典序
    };
    sort(events.begin(),events.end(),cmp);
    for(auto& e:events){
    int curr_t=stoi(e[1]); // 当前时间
    string& mention=e[2];
    if(e[0][0]=='O'){ //离线事件
    online_t[stoi(mention)]=curr_t+60; // 下次在线时间
    }
    //消息事件
    else if(mention[0]=='A'){ // @所有人
    for(int i=0;i<numberOfUsers;i++) ans[i]++;
    }
    else if(mention[0]=='H'){ // @所有在线用户
    for(int i=0;i<numberOfUsers;i++){
    if(curr_t>=online_t[i]) ans[i]++;
    }
    }
    else{ // @id
    int idx=0;
    for(int i=0;i<mention.size();i++){
    if(isdigit(mention[i])) idx=idx*10+(mention[i]-'0');
    if(i+1==mention.size() || mention[i+1]==' '){
    ans[idx]++;
    idx=0;
    }
    }
    }
    }

    复制代码
          return ans;
      }

    };

相关推荐
I_LPL23 分钟前
day21 代码随想录算法训练营 二叉树专题8
算法·二叉树·递归
可编程芯片开发30 分钟前
基于PSO粒子群优化PI控制器的无刷直流电机最优控制系统simulink建模与仿真
人工智能·算法·simulink·pso·pi控制器·pso-pi
cpp_250131 分钟前
P8448 [LSOT-1] 暴龙的土豆
数据结构·c++·算法·题解·洛谷
YGGP32 分钟前
【Golang】LeetCode 49. 字母异位词分组
leetcode
lcj251132 分钟前
深入理解指针(4):qsort 函数 & 通过冒泡排序实现
c语言·数据结构·算法
fie888933 分钟前
基于MATLAB的转子动力学建模与仿真实现(含碰摩、不平衡激励)
开发语言·算法·matlab
唐梓航-求职中40 分钟前
编程大师-技术-算法-leetcode-1472. 设计浏览器历史记录
算法·leetcode
_OP_CHEN43 分钟前
【算法基础篇】(五十八)线性代数之高斯消元法从原理到实战:手撕模板 + 洛谷真题全解
线性代数·算法·蓝桥杯·c/c++·线性方程组·acm/icpc·高斯消元法
YGGP1 小时前
【Golang】LeetCode 1. 两数之和
leetcode
唐梓航-求职中1 小时前
编程大师-技术-算法-leetcode-355. 设计推特
算法·leetcode·面试