我有一个可变行和列数的二维数组.数组作为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);
Inm小程序商店
Inm小程序商店收录了最新,最热门的微信小程序和微信小游戏,是国内内容最丰富的集小程序游戏、小程序分发、小程序推广为一体的综合性小程序门户网站之一。
Vultr中文网
最低 $2.5/月 的VPS, 稳定, 可靠