Java 如何使此代码在O(c.size()+;n-I)时间内运行? 公有布尔ALADALL(int i,集合< p>),而不是一次添加一个项目,考虑以下事项: 确保数据结构中有足够的空间容纳所有新元素 将位置i处的所有元素向下移动一个与要添加的新元素数相等的空格数。这可以在时间O(1+n-i)内完成,因为每个项目只移动一次 写下要插入到新点中的元素
总的来说,这需要时间O(n-i+k+1),其中n是原始数据结构中的元素数,i是插入的位置,k是插入的新元素数。关键的优点是您一次完成所有移位,而不是进行大量的较小移位Java 如何使此代码在O(c.size()+;n-I)时间内运行? 公有布尔ALADALL(int i,集合< p>),而不是一次添加一个项目,考虑以下事项: 确保数据结构中有足够的空间容纳所有新元素 将位置i处的所有元素向下移动一个与要添加的新元素数相等的空格数。这可以在时间O(1+n-i)内完成,因为每个项目只移动一次 写下要插入到新点中的元素,java,performance,data-structures,big-o,Java,Performance,Data Structures,Big O,总的来说,这需要时间O(n-i+k+1),其中n是原始数据结构中的元素数,i是插入的位置,k是插入的新元素数。关键的优点是您一次完成所有移位,而不是进行大量的较小移位 希望这有帮助!列表是如何实现的?它是作为一个ArrayRequest实现的。要改变一个具体数据结构设计的性能特征真的很难。当你想要一个动态数组的简单性和快速访问性时,你必须处理副本。链表可以快速地进行所有修改,但通常速度较慢而且随机访问速度非常慢。如果你想两者兼而有之,我会看看间隙缓冲区或绳索。请问我如何创建空间?如果没有看到代码
希望这有帮助!列表是如何实现的?它是作为一个ArrayRequest实现的。要改变一个具体数据结构设计的性能特征真的很难。当你想要一个动态数组的简单性和快速访问性时,你必须处理副本。链表可以快速地进行所有修改,但通常速度较慢而且随机访问速度非常慢。如果你想两者兼而有之,我会看看间隙缓冲区或绳索。请问我如何创建空间?如果没有看到代码,很难说。看看现有的add()函数是如何保留空间的,看看你是否能适应它。我尝试过调整它的大小,但仍然给我出边界的例外
public boolean addAll(int i, Collection<? extends T> c) {
for (T x : c)
add(i++, x);
return true;
}
/**
* Array used to store elements
*/
protected T[] a;
/**
* Index of next element to de-queue
*/
protected int j;
/**
* Number of elements in the queue
*/
protected int n;
/**
* Grow the internal array
*/
protected void resize() {
T[] b = f.newArray(Math.max(2*n,1));
for (int k = 0; k < n; k++)
b[k] = a[(j+k) % a.length];
a = b;
j = 0;
}
/**
* Constructor
*/
public ArrayDeque(Class<T> t) {
f = new Factory<T>(t);
a = f.newArray(1);
j = 0;
n = 0;
}
public int size() {
return n;
}
public T get(int i) {
if (i < 0 || i > n-1) throw new IndexOutOfBoundsException();
return a[(j+i)%a.length];
}
public T set(int i, T x) {
if (i < 0 || i > n-1) throw new IndexOutOfBoundsException();
T y = a[(j+i)%a.length];
a[(j+i)%a.length] = x;
return y;
}
public void add(int i, T x) {
if (i < 0 || i > n) throw new IndexOutOfBoundsException();
if (n+1 > a.length) resize();
if (i < n/2) { // shift a[0],..,a[i-1] left one position
j = (j == 0) ? a.length - 1 : j - 1; // (j-1) mod a.length
for (int k = 0; k <= i-1; k++)
a[(j+k)%a.length] = a[(j+k+1)%a.length];
} else { // shift a[i],..,a[n-1] right one position
for (int k = n; k > i; k--)
a[(j+k)%a.length] = a[(j+k-1)%a.length];
}
a[(j+i)%a.length] = x;
n++;
}
public T remove(int i) {
if (i < 0 || i > n - 1) throw new IndexOutOfBoundsException();
T x = a[(j+i)%a.length];
if (i < n/2) { // shift a[0],..,[i-1] right one position
for (int k = i; k > 0; k--)
a[(j+k)%a.length] = a[(j+k-1)%a.length];
j = (j + 1) % a.length;
} else { // shift a[i+1],..,a[n-1] left one position
for (int k = i; k < n-1; k++)
a[(j+k)%a.length] = a[(j+k+1)%a.length];
}
n--;
if (3*n < a.length) resize();
return x;
}
public void clear() {
n = 0;
resize();
}