如何在常量时间内实现支持以下内容的数据结构 . 我在面试时得到了这个问题,以下是我的解决方案 . 如果您有方法,请检查我的方法,或建议更好的替代方法 .
////////////////////////////////////////////////////////////////
// Implement a container that have the following methods:
// Java:
// public class Container<E>
// {
// // data memebers
// ...
// public Container();
// // constructor
// // Complexity: Constant
//
// public int size();
// // return the total number of elements in the container
// // Complexity: Constant
//
// public E get(int index);
// // get an element from the container by its index
// // Complexity: Constant
//
// public void set(int index, E element);
// // set an element in the container by its index. index >= 0 && index < size()
// // Complexity: Constant
//
// public void add_front (E element);
// // add a new element to the front of the container i.e. its index is 0
// // Complexity: Constant (amortized time)
//
// public void remove_front ();
// // remove the element at the front of the container
// // Complexity: Constant
//
// public void add_back (E element);
// // add a new element to the back of the container i.e. its index is size()
// // Complexity: Constant (amortized time)
//
// public void remove_back ();
// // remove the element at the back of the container
// // Complexity: Constant
// }
//
// Examples:
// at beginning => []
// add_front(0) => [0]
// add_front(-1) => [-1, 0]
// add_back(1) => [-1, 0, 1]
// add_back(2) => [-1, 0, 1, 2]
// get(0) => -1
// get(3) => 2
// set(3, 8) => [-1, 0, 1, 8]
// remove_front() => [0, 1, 8]
// remove_back() => [0, 1]
////////////////////////////////////////////////////////////////
My approach 使用Hashtable存储值 . Hashtable storage = new Hashtable <>();有两个名为front和back的变量,表示数据结构存储范围的开始和结束 .
- add_front(E元素)
低 - ;
storage.put(low,element);
- add_back(E元素)
高; storage.put(high,element);
- public void remove_front();
低;
- public void remove_back();
高 - ;
- public E get(int index);
index = index-low; return storage.get(index);
- public void set(int index,E element);
index = index-low; storage.put(index,element);
- public int size();
返回高 - 低1;
1 回答
由于add_front()和add_back()的复杂性需要分摊常量,并且在remove_front()和remove(back)之后不需要内存效率,因此可以使用数组!它们比哈希表更简单,并且在运行时复杂性中没有“高概率” .
您可以从大小为3的数组开始,将第一个元素放在中间,这样您就可以有一个add_front和一个add_back . 然后当它溢出时,只需移动大小为6的数组中间的元素 . 通常是spaking,每次溢出时都会使数组大小加倍 .
您显然需要通过数据结构中的某些整数变量跟踪数组的开始和结束位置及其当前容量 .