gpt4 book ai didi

java - 在java中的二维数组中的指定位置插入元素或删除元素

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:33:28 25 4
gpt4 key购买 nike

我有一个行数和列数可变的二维数组。该数组在数据库中存储为 JSON。我需要在用户指定的某个元素之后添加给定元素或删除用户指定的元素。数组中的每个元素都是唯一的。示例 json 值类似于 [[4,5],[3,1,6,7],[34,21,55]]。考虑我想在元素 7 之后添加 2 个元素 12,13 的情况,结果数组看起来像 [[4,5],[3,1,6,7,12,13],[34,21 ,55]]。如果我给 1 作为输入,要删除结果应该是 [[4,5],[3,6,7,12,13],[34,21,55]]。使用 Gson 我已经解析存储到数组中的 json 值。我怎样才能以更少的时间复杂度在 Java 中实现它。

我从数据库中解析 json 数据的代码看起来像

Gson gson = new GsonBuilder().create();
if (myTemplate.getQuestionOrder() != null) {
long[][] questionOrder = gson.fromJson(myTemplate.getQuestionOrder(), long[][].class);
}

最佳答案

试试下面的方法。

private static void insertAfter(long[][] array, int value, long[] insertion) {
boolean found = false;
for (int i = 0; i < array.length; i++) {
long[] sub = array[i];
for (int j = 0; j < sub.length; j++) {
if (sub[j] == value) {
long[] newSub = new long[sub.length + insertion.length];
System.arraycopy(sub, 0, newSub, 0, j + 1);
System.arraycopy(insertion, 0, newSub, j + 1, insertion.length);
System.arraycopy(sub, j + 1, newSub, j + 1 + insertion.length, sub.length - j - 1);
array[i] = newSub;
found = true;
break;
}
}
if (found) break;
}
}

示例用法:

insertAfter(questionOrder, 7, new long[]{12, 13});
System.out.println(gson.toJson(questionOrder));

这将打印 [[4,5],[3,1,6,7,12,13],[34,21,55]]

要删除元素,您可以使用类似但略有修改的逻辑:

private static long[][] remove(long[][] array, int value) {
boolean found = false;
int emptyIndex = -1;
for (int i = 0; i < array.length; i++) {
long[] sub = array[i];
for (int j = 0; j < sub.length; j++) {
if (sub[j] == value) {
long[] newSub = new long[sub.length - 1];
System.arraycopy(sub, 0, newSub, 0, j);
System.arraycopy(sub, j + 1, newSub, j, sub.length - j - 1);
array[i] = newSub;
if (array[i].length == 0) emptyIndex = i;
found = true;
break;
}
}
if (found) break;
}
if (emptyIndex >= 0) {
long[][] newArray = new long[array.length - 1][];
System.arraycopy(array, 0, newArray, 0, emptyIndex);
System.arraycopy(array, emptyIndex + 1, newArray, emptyIndex, array.length - emptyIndex - 1);
array = newArray;
}
return array.length == 0 ? null : array;
}

此方法将从内部数组中删除给定的项目,如果内部数组变为空,则将其从外部数组中删除。它返回修改后的数组,如果它为空,则返回 null

示例用法:

questionOrder = remove(questionOrder, 4);

关于java - 在java中的二维数组中的指定位置插入元素或删除元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48635549/

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