我们需要实现一个叫 DataStream
的数据结构。并且这里有 两
个方法需要实现:
void add(number)
// 加一个新的数int firstUnique()
// 返回第一个独特的数
样例
例1:
输入:
add(1)
add(2)
firstUnique()
add(1)
firstUnique()
输出:
[1,2]
例2:
输入:
add(1)
add(2)
add(3)
add(4)
add(5)
firstUnique()
add(1)
firstUnique()
add(2)
firstUnique()
add(3)
firstUnique()
add(4)
firstUnique()
add(5)
add(6)
firstUnique()
输出:
[1,2,3,4,5,6]
注意事项
你可以假设在调用 firstUnique 方法时,数据流中至少有一个独特的数字
class DataStream {
public:
vector<int> nums;
DataStream(){
// do intialization if necessary
}
/**
* @param num: next number in stream
* @return: nothing
*/
void add(int num) {
// write your code here
//nums = nums + to_string(num);
nums.push_back(num);
}
/**
* @return: the first unique number in stream
*/
int firstUnique() {
// write your code here
int index = firstUniqChar(nums);
//cout<<index<<endl;
return nums[index];
}
int firstUniqChar(vector<int> &s) {
// write your code here
unordered_map<int, int> mymap;
for(int i = 0; i < s.size(); i++)
{
mymap[s[i]]++;
}
int ch = 0;
int ret = INT_MAX;
for(auto it = mymap.begin(); it != mymap.end(); it++)
{
//cout<<it->first;
if(it->second == 1)
{
ch = it->first;
//break;
for(int i = 0; i < s.size(); i++)
{
if(s[i] == ch)
{
ret = min(ret, i);
break;
}
}
}
}
if(ch == 0)
return -1;
//cout<<ch<<endl;
return ret;
}
};