对于学校,我必须在java中构建一个使用RLE(行程编码)压缩数组的方法。我无法在网上找到解决方案,因为我的老师希望我自己解决问题。不幸的是,我不能这样做,因为我是一个忙碌的人,有一些繁忙的计划。
RLE将此:{1,1,1,1,2,2,3,3,6,6,6,7,8,8,8}改为:{4,1,2,2,2,3 ,3,6,1,7,3,8}它基本上是一个新的数组,遵循这个公式{这个值的#,这个值,这个值的#,这个值,续...}有4个1 {4,1}你得到我的漂移。
这是我试图做的事情(请原谅我的蹩脚代码,我只是一名高中生):
public class tester{
public static void main(String[] args){
int[] potato = {1,1,1,2,2,4,4,4,6,6,6,6};
printArray(compress(potato));
}
public static void printArray(int[] arr){
for(int i = 0; i < arr.length; i++){
System.out.println(arr[i]);
}
}
public static int[] compress(int[] a) {
//figure out how many different numbers there are.
int diffNums = 1;
for(int i = 0; i < a.length; i++){
if(i != a.length-1 && a[i] != a[i+1]){
diffNums++;
}
}
//make compressed array at the correct length.
int[] compressed = new int[diffNums * 2];
//figure out what each number is.
int[] nums = new int[diffNums];
nums[0] = a[0];
int spot = 0;
for(int i = 0; i < a.length; i++){
if(i != a.length-1 && a[i] != a[i+1]){
nums[spot] = a[i+1];
}
}
//figure out quantity of each number.
int[] quantities = new int[diffNums];
int spot2 = 0;
int spotcur = 0;
for(int i = 0; i < diffNums; i++){
int quant = 0;
while(a[spotcur] == a[spot2]){
quant++;
spotcur++;
}
spot2 = spotcur;
quantities[i] = quant;
}
//add them together and return compressed array
int spotter = 0;
for(int i = 0; i < diffNums; i++){
compressed[spotter] = quantities[i];
spotter++;
compressed[spotter] = nums[i];
spotter++;
}
return compressed;
}
}
有谁知道我怎么能修复这个糟糕的代码?我被困在上面