Hi I know it's bascially a hash table, but since it ask for iterate time is O(number of elements) rather than O(size of array). Any thoughts?
Detail requirements:
- Use array-like data strcutre only
- Achieve the below time compleixty:
Add:O(1) time
Delete: O(1) time
Search: O(1) time
Clear: O(1) time
Iterate: O(number of elements)
Below is my solution:
public class myDS
{
public LinkedList<int> idxArr;
public HashEntry[] eleArr;
private int capacity = 251; //Some random prime number
//Constructor
public myDS()
{
eleArr = new HashEntry[capacity];
/*for (int i = 0; i < capacity; i++) Not sure if we need it.
{
eleArr[i] = null;
}*/
idxArr = new LinkedList<int>();
}
//Add
public void Add(int key, int value)
{
int hash = key % capacity;
while (eleArr[hash] != null && eleArr[hash].GetKey() != key)
{
hash = (hash + 1) % capacity;
}
eleArr[hash] = new HashEntry(key, value);
idxArr.AddFirst(hash);
}
//Search
public int Get(int key)
{
int hash = key % capacity;
while (eleArr[hash] != null && eleArr[hash].GetKey() != key)
{
hash = (hash + 1) % capacity;
}
//Not exist
if (eleArr[hash] == null)
return -1;
else
return eleArr[hash].GetValue();
}
//Clear, is it a true O(1) time?
public void Clear()
{
var newEleArr = new HashEntry[capacity];
var newIdxArr = new LinkedList<int>();
eleArr = newEleArr;
idxArr = newIdxArr;
}
//Delete
public void Delete(int key)
{
int hash = key % capacity;
eleArr[hash] = null;
//How to delete a element in the linked list in O(1) time??
}
//Iterator
public void Iterate()
{
var idxEnumerator = idxArr.GetEnumerator();
while (idxEnumerator.MoveNext() && idxEnumerator.Current != null)
{
int idx = idxEnumerator.Current;
if (eleArr[idx] != null)
{
Console.WriteLine("Key: " + eleArr[idx].GetKey() + "Value: " + eleArr[idx].GetValue());
}
}
}
}