我有一个可变数量的行和列的二维数组。该数组作为JSON存储在数据库中。我有一个requiremnt在用户指定的某个元素之后添加给定元素或删除用户指定的元素。阵列中的每个elemet都是独一无二的。示例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中实现它。
我从db解析json数据的代码看起来像
Gson gson = new GsonBuilder().create();
if (myTemplate.getQuestionOrder() != null) {
long[][] questionOrder = gson.fromJson(myTemplate.getQuestionOrder(), long[][].class);
}
答案 0 :(得分:3)
尝试以下方法。
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);