这是我的第一个StackOverflow问题,如果我没有遵循社区准则或者应该删除它,请让我知道。
我得到了自己的第一道面试题,但是因为我的实现被拒绝了。
问题是:
设计并实现一个C++类,存储整数集合。在构造时,集合应为空。相同的数字可能会被存储多次。
实现以下方法:
Insert(int x)。插入一个值为“x”的条目。
Erase(int x)。从集合中删除一个值为“x”的条目(如果存在)。
Erase(int from, int to)。删除所有值在范围[from,to]中的条目。
Count(int from, int to)。计算具有范围[from,to]中的值的条目数。
我认为一个好的实现方式是使用链表,因为它使用非连续内存,而且删除条目不需要移动大量数据(如向量或数组中的数据)。然而,我收到了公司的反馈,说我的实现时间复杂度为O(n^2),效率很低,所以我被拒绝了。如果在另一个面试中出现类似的问题,我不想重复同样的错误,所以我想知道如何最好地解决这个问题(一个朋友建议使用map,但他也不确定)。
我的代码是:
void IntegerCollector::insert(int x)
{
entries.push_back(x);
}
void IntegerCollector::erase(int x)
{
list<int>::iterator position = find(entries.begin(), entries.end(), x);
if (position != entries.end())
entries.erase(position);
}
void IntegerCollector::erase(int from, int to)
{
list<int>::iterator position = entries.begin();
while (position != entries.end())
{
if (*position >= from && *position <= to)
position = entries.erase(position);
else
position++;
}
}
int IntegerCollector::count(int from, int to)
{
list<int>::iterator position = entries.begin();
int count = 0;
while (position != entries.end())
{
if (*position >= from && *position <= to)
count++;
position++;
}
return count;
}
反馈提到他们只会雇用能够使用O(nlogn)复杂度实现解决方案的候选人。