[英]Trouble splitting an array of integers using a delimiter
我正在写一个方法,该方法将输入一个整数数组和一个作为定界符的整数作为输入。 它根据定界符分割数组,并返回一个2D数组,以便每一行都包含数组中的数字,直到定界符(不包括定界符)为止。
例子:
输入:
{1, 2, 3, 1, 2, 3, 1, 1, 2, 2, 3, 1}, 3
输出:
[1, 2]
[1, 2]
[1, 1, 2, 2]
[1]
输入: {3, 1, 3, 3}, 3
输出: [1]
但是相反,当我运行代码时,我没有得到任何回报,而是在调试模式下运行了它,结果是[null, null, [1, 2]]
我应该在代码中解决什么?
public static int[][] splitArrayByNum(int[] input, int number) {
if (input[0] == number)
for (int i = 0; i < input.length - 1; i++) {
input[i] = input[i + 1];
}
if ((input[(input.length) - 1]) == number)
for (int i = (input.length) - 1; i < input.length - 1; i++) {
input[i] = input[i + 1];
}
int count = 0;
for (int i = 0; i < input.length; i++)
if (input[i] == number) {
count++;
}
int[][] result = new int[count][];
int firstindex = 0;
int lastindex = 0;
for (int j = 0; j < input.length; j++) {
if (input[j] == number) {
result[j] = Arrays.copyOfRange(input, firstindex, lastindex);
firstindex = lastindex = j;
}
lastindex++;
}
return result;
}
好吧,我对此有所了解,其他人可以提出一些更优雅的建议吗,这似乎并不像它那么简单吗?
public static int[][] arraySplitByDelimiter(int[] inputArray, int delimiter) {
//Make an array to hold our results, ideally it would be nice to use an ArrayList
//so that it can expand dynamically but instead we can also make one that we know will be big enough
//if every other int is a delimiter then we can end up with a result array of inputArray.length / 2
int[][] temporaryResultArray = new int[inputArray.length / 2][];
int numberOfResultArrays = 0;
int lastDelimterPosition = 0;
for (int i = 0; i < inputArray.length; i++) {
//If we find a delimeter copy the chunk of the input array to a new array in the temporaryResultArray
if (inputArray[i] == delimiter) {
temporaryResultArray[numberOfResultArrays++] = Arrays.copyOfRange(inputArray, lastDelimterPosition, i);
lastDelimterPosition = i + 1;
} else if (i == (inputArray.length - 1)) {
//If we're at the end of the array then we should copy the last chunk to new array
temporaryResultArray[numberOfResultArrays++] = Arrays.copyOfRange(inputArray, lastDelimterPosition, inputArray.length);
}
}
int[][] finalResultArray = new int[numberOfResultArrays][];
for (int i = 0; i < numberOfResultArrays; i++) {
finalResultArray[i] = temporaryResultArray[i];
}
return finalResultArray;
}
只是为了说明流程逻辑:
int[][] result = new int[][];
int resultIndex = 0;
int[] chunk = new int[];
int chunkIndex = 0;
for (int i=0; i<input.length; i++) {
if (input[i] != number) {
chunk[chunkIndex++] = input[i];
}
else {
if (chunk.length > 0) {
result[resultIndex++] = chunk;
chunk = new int[];
chunkIndex = 0;
}
}
}
if (chunk.length > 0) {
result[resultIndex] = chunk;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.