如果一个数组在相邻位置包含相同的数字,它们将被合并为一个数字,如下面的示例输入和输出中的那个值加倍。
int[] test = {2,0,2,4,0,0,4};
Tile.alter(test)
true
test
{ 4, 8, 0, 0, 0, 0, 0 } //(the two 2’s merged, and the two 4’s merged)
int[] test = {2,0,4,2,0,0,4};
Tile.alter(test)
true
test
{ 2, 4, 2, 4, 0, 0, 0 } //(nothing merged – the 2’s are not adjacent, nor are the 4’s)
我尝试了这个并且它不起作用:
int curr=size[i];
if(size.length<=0)
int prev = size[0];
size[0]=size[0]*size[1];
for(int j = 0;j<size.length;j++)
size[j]=prev*size[j+1];
prev=curr;
size[size.length-1]=prev *size[size.length-1];
答案 0 :(得分:0)
所以我真的不明白你想要做什么,但这是我的猜测:
您从数组开始
int[] a = {/*Some numbers*/};
然后将数组的值向左移动,直到它具有块的总和。
for (int i = 0, index = 0, current = a[0]; i < a.length; i++) {
if (a[i] == 0) {
continue;
} else if (current == 0) {
current = a[i];
}
if (a[i] == current) {
a[index] += current;
} else {
index++;
current = a[i];
a[index] = current;
}
if (i != index) {
a[i] = 0;
}
}
如果我的所有假设都是正确的,这可能有用(我没有测试过)。如果需要使用新数组,那么只需在启动之前克隆一个。
答案 1 :(得分:0)
这个问题可以通过多种方式解决,但对于干净且易于理解的代码,我建议使用以下方法:
首先将中间零移到末尾,这样就可以使非零元素彼此相邻。例如:
[2, 0, 2, 4, 0, 0, 4] => [2, 2, 4, 4, 0, 0, 0]
两个一个地进行可能的合并,因为您不需要链合并:
[2, 2, 4, 4, 0, 0, 0] => [4, 0, 8, 0, 0, 0, 0]
再次将中间零移到最后:
[4, 0, 8, 0, 0, 0, 0] => [4, 8, 0, 0, 0, 0, 0]
由于上述每个阶段都可以在阵列上使用一次迭代完成,因此整个算法来自O(n)
。
您可以按如下方式找到算法实现:
import java.util.Arrays;
public class MergeAdjacent {
private static int[] mergeLeft(int[] original) {
int[] zeroShiftedForMerge = shiftZerosToRight(original);
//
for (int i = 0; i < zeroShiftedForMerge.length-1; i++) {
if(zeroShiftedForMerge[i] == 0)
break;
if(zeroShiftedForMerge[i] == zeroShiftedForMerge[i+1]) {
zeroShiftedForMerge[i] += zeroShiftedForMerge[i+1];
zeroShiftedForMerge[i+1] = 0;
i++;
}
}
//
return shiftZerosToRight(zeroShiftedForMerge);
}
private static int[] shiftZerosToRight(int[] original) {
int[] zeroShifted = new int[original.length];
int ind = 0;
for (int i = 0; i < original.length ; i++) {
if(original[i] != 0) {
zeroShifted[ind++] = original[i];
}
}
return zeroShifted;
}
public static void main(String[] args) {
int[] test1 = {2,0,2,4,0,0,4};
int[] test2 = {2,0,4,2,0,0,4};
int[] test3 = {2,0,0,2,0,0,4};
int[] test4 = {2,0,4,2,0,0,2};
int[] test5 = {4,0,4,4,2,0,4};
//
int[] merged1 = mergeLeft(test1);
int[] merged2 = mergeLeft(test2);
int[] merged3 = mergeLeft(test3);
int[] merged4 = mergeLeft(test4);
int[] merged5 = mergeLeft(test5);
//
System.out.println(Arrays.toString(test1) +" => "+ Arrays.toString(merged1));
System.out.println(Arrays.toString(test2) +" => "+ Arrays.toString(merged2));
System.out.println(Arrays.toString(test3) +" => "+ Arrays.toString(merged3));
System.out.println(Arrays.toString(test4) +" => "+ Arrays.toString(merged4));
System.out.println(Arrays.toString(test5) +" => "+ Arrays.toString(merged5));
}
}
运行上面的程序以查看输入和输出:
[2,0,2,4,0,0,4] =&gt; [4,8,0,0,0,0,0]
[2,0,4,2,0,0,4] =&gt; [2,4,2,4,0,0,0]
[2,0,0,2,0,0,4] =&gt; [4,4,0,0,0,0,0]
[2,0,4,2,0,0,2] =&gt; [2,4,4,0,0,0,0]
[4,0,4,4,2,0,4] =&gt; [8,4,2,4,0,0,0]
希望这会有所帮助。