gpt4 book ai didi

java - 向动态数组的左侧和右侧添加问题

转载 作者:行者123 更新时间:2023-12-02 10:00:25 26 4
gpt4 key购买 nike

所以我尝试用 Java 创建一个动态数组。对于这个问题,有一个名为 store 的主数组,它具有已定义的大小。存储内有一种伪数组,它利用存储 block 作为动态数组。左变量和右变量是分别充当动态数组的头和尾的索引。这意味着 left 的值是 store 中动态数组开始的索引,而 right 的值是结束。

我一直在尝试为此创建 addleft 和 addright 方法,但我不断出现越界错误。但是,我不确定我到底错在哪里。

    boolean add(int i, int x){
if (i<0 || i>size) return false;
if (i<size-i)
addLeft(i,x);
else
addRight(i,x);
return true;
}//add
void addLeft(int i, int x){
size ++;
left--;
if(left == -1) {
restore();
}
for(int j = left; j < left + i; j++) {
store[j] = store[j+1];
}
store[left + 1 + i] = x;
return;
}//addLeft
void addRight(int i, int x){
size ++;
right++;
if(right == CAP+1) {
restore();
}
for(int j = right; j > left + i; j--) {
store[j] = store[j-1];
}
store[left + 1 + i] = x;
return;
}//addRight

我正在寻找的结果是输入要插入到索引处的整数,然后向左(对于addleft)或向右(对于addright)的值移动到各自的方向。当动态数组的一侧到达末尾时,restore() 方法用于扩展存储数组。

最佳答案

对数据类型进行了一些假设,并用 system.out 命令替换了您的函数。我在 for 循环中遇到了超出界限的异常,所以我认为您的错误在于名为 store store[j] = store[j+1]; 的数组,for 循环范围之外的行是也出界:store[left + 1 + i] = x;

这是一个有根据的猜测,如果您可以发布整个代码,我将运行它并希望能给出更好的答案!不确定变量 size、left、right、store[] 和 CAP 是什么。

更新:

更新 addRight 方法后能够让程序运行。从商店创建了一个大小为 +1 的临时数组。存储然后克隆温度。这是我关于如何使用 addRight 方法的想法。

void addRight(int i, int x){
size++;
right++;
if(right == CAP+1) {
restore();
}
int[] temp;
temp = new int[store.length+1];

for(int j = 0; j <= store.length; j++) {
if(j < i){
temp[j] = store[j];
}
else if (j == i) {
temp[j] = x;
}
else if( j > i)
{
temp[j] = store[j-1];
}
}
store = new int [temp.length];
for(int k = 0; k < temp.length; k++)
{
store[k] = temp[k];
}
return;

关于java - 向动态数组的左侧和右侧添加问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55672481/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com