leetcode题目链接 https://leetcode-cn.com/problems/first-unique-number/
代码:
class FirstUnique
{
public:
unordered_map<int,int> num_freq;
vector<int> rec;
FirstUnique(vector<int>& nums)
{
for (int x: nums)
num_freq[x] ++;
for (int x : nums)
if (num_freq[x] == 1)
rec.push_back(x);
}
int showFirstUnique()
{
int n = rec.size();
int res = -1;
int i = 0;
while (i < n)
{
if (num_freq[rec[i]] == 1)
{
res = rec[i];
rec.erase(rec.begin(), rec.begin() + i);
break;
}
i ++;
}
return res;
}
void add(int value)
{
num_freq[value] ++;
if (num_freq[value] == 1)
{
rec.push_back(value);
}
}
};
/**
* Your FirstUnique object will be instantiated and called as such:
* FirstUnique* obj = new FirstUnique(nums);
* int param_1 = obj->showFirstUnique();
* obj->add(value);
*/
求解释中rec.erase(rec.begin(), rec.begin() + i);的作用,我个人理解map中本就保存不重复的元素,这一句的意思应该是指删除因为新添加元素而变成不是唯一整数的数据,因为这个程序中只差这一个功能了,但是我没有理解到,谢谢!
while (i < n)
{
if (num_freq[rec[i]] == 1)
{
res = rec[i];
rec.erase(rec.begin(), rec.begin() + i);
break;
}
i ++;
}