First Unique Number in a Stream II-LintCode

本文介绍了一种名为DataStream的数据结构的实现方法,该结构支持添加新数值(add)与获取首个唯一数值(firstUnique)的操作。通过结合使用集合与队列,确保了高效地处理重复数值并快速检索首个唯一数值。

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

We need to implement a data structure named DataStream. There are two methods required to be implemented:

  1. void add(number) // add a new number
  2. int firstUnique() // return first unique number
 注意事项
You can assume that there must be at least one unique number in the stream when calling the firstUnique.

样例

add(1)
add(2)
firstUnique() => 1
add(1)
firstUnique() => 2

思路

#ifndef C960_H
#define C960_H
#include<iostream>
#include<set>
#include<queue>
using namespace std;
class DataStream {
public:

    DataStream(){
        // do intialization if necessary
    }

    /**
    * @param num: next number in stream
    * @return: nothing
    */
    void add(int num) {
        // write your code here
        //如果num不是第一次出现,在two中添加num
        //否则将num入队并在dic中添加num
        if (dic.find(num) != dic.end())
        {
            two.insert(num);
        }
        else
        {
            que.push(num);
            dic.insert(num);
        }
        //如果队头元素出现至少两次,出队
        while (!que.empty() && two.find(que.front()) != two.end())
        {
            que.pop();
        }       
    }
    /**
    * @return: the first unique number in stream
    */
    int firstUnique() {
        // write your code here
        return que.front();//直接返回队头
    }
    set<int> two, dic;//two中存放至少出现两次的数,dic中存放所有出现的数
    queue<int> que;
};
#endif
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值