我想解决一个关于HashSet设计的问题。
在不使用任何内置哈希表库的情况下设计HashSet。 具体来说,您的设计应该包括以下两个功能: add( value ):在HashSet中插入一个值。 包含(值):返回值是否存在于HashSet中。 删除(值):删除HashSet中的值。如果HashSet中不存在该值,则不执行任何操作。 示例: MyHashSet hashSet =新MyHashSet();hashSet.add(1); hashSet.add(2);hashSet.contains(1);//返回真hashSet.contains(3);//返回假(未找到) hashSet.add(2); hashSet.contains(2);//返回真hashSet.remove(2); hashSet.contains(2);//返回false (已删除) 注意: 所有的值都在1,1000000之间。操作的数量将在1,10000的范围内。请不要使用内置的HashSet库.
以下代码在本地运行良好,但在提交错误时失败,
运行时错误消息:对于“int”类型,引用绑定到错误对齐地址0x736c61662c657572,这需要4字节对齐 最后执行输入:"MyHashSet“、”添加“、”删除“、”添加“、”包含“、”添加“、”删除“、”添加“、”6、4、17、14、14、14、14、18、14]
class MyHashSet { public:
vector<vector<int>> setHash;
MyHashSet() {
setHash.reserve(10000);
}
void add(int key) {
int bucket = key % 10000;
vector<int>::iterator it;
it = find(setHash[bucket].begin(),setHash[bucket].end(),key);
if(it == setHash[bucket].end()){
setHash[bucket].push_back(key);
}
}
void remove(int key) {
int bucket = key % 10000;
vector<int>::iterator it1;
it1 = find(setHash[bucket].begin(),setHash[bucket].end(),key);
if(it1 != setHash[bucket].end()){
int index = distance(it1,setHash[bucket].begin());
setHash[bucket].erase(setHash[bucket].begin()+index);
}
}
/** Returns true if this set did not already contain the specified element */
bool contains(int key) {
int bucket = key % 10000;
vector<int>::iterator it2;
it2 = find(setHash[bucket].begin(),setHash[bucket].end(),key);
if(it2 != setHash[bucket].end()){
return true;
}
return false;
}};
我怀疑是因为记忆问题。但由于我仍在学习c++的基本原理,我无法理解。
发布于 2018-07-12 03:41:11
如果您的问题是如何修复您的实现,我将听取评论中的建议。
如果您希望了解C++并以最佳方式解决问题,我将使用std::bitset。事实上他们给了你定义的输入范围1,1000000,这让我相信他们在寻找这样的东西。
这可能属于内置哈希表库的类别,因此here is a potential implementation。
class MyHashSet {
public:
void add(int key) {
flags.set(key);
}
void remove(int key) {
flags.reset(key);
}
bool contains(int key) const {
return flags[key];
}
private:
bitset<1000000+1> flags;
};在我的平台上,这占用了~16 as(相对于10000向量的30kB+ )。它还不需要动态内存分配。
如果您认为这是非主题或作弊,请提供标题/号码的LeetCode问题,以便我可以工作在您的代码草案使用他们的测试用例。我现在也在研究哈希表,这样就可以双赢了。
https://stackoverflow.com/questions/51296228
复制相似问题