我需要一些帮助来计算数组中相邻元素的数量。
假设我有 4 个整数数组。
myArray = {1, 1, 1, 1}
myArray2 = {5, 6, 7, 8, 7, 1, 10, 11, 12};
myArray3 = {5, 6, 7, 7, 8, 1, 10, 11, 12};
myArray4 = {5, 6, 7, 7, 8, 1, 10, 11, 11, 11, 12};
我想计算这些数组中元素的数量。
期望的输出应该是:
myArray => 1 (1 bunch of adjacent element "1")
myArray2 => 0 (no adjacent element)
myArray3 => 1 (1 bunch of adjacent element "7")
myArray4 => 2 (2 bunches of adjacent elements "7" and "11")
我可以计算相邻元素的数量,但不能计算成串的数量。
这是我编写的代码:
import acm.program.ConsoleProgram;
public class project extends ConsoleProgram{
public void run ()
{
int[] myArray = {1, 1, 1, 1};
int[] myArray2 = {5, 6, 7, 8, 7, 1, 10, 11, 12};
int[] myArray3 = {5, 6, 7, 7, 8, 1, 10, 11, 12};
int[] myArray4 = {5, 6, 7, 7, 8, 1, 10, 11, 11, 11, 12};
println("myArray -> " + countBunches(myArray));
println("myArray2 -> " + countBunches(myArray2));
println("myArray3 -> " + countBunches(myArray3));
}
public int countBunches(int[] myArray)
{
int count = 0;
int saveIndex;
int saveContent;
for(int i = 0; i<myArray.length; i++)
{
if(i == 0)
{
saveContent = myArray[i];
}
else
{
saveContent = myArray[i-1];
if(saveContent == myArray[i])
{
saveContent = myArray[i];
saveIndex = i;
count++;
println(myArray[saveIndex] + " repatingb" + saveIndex + ". element");
}
else
{
saveContent = myArray[i];
}
}
}
return(count);
}
}
最佳答案
问题在于,每次一个元素与最后一个元素匹配时,您都会进行计数。因此,如果连续有 3 个相同的项目,则算作 2,而不是 1。
一种方法是跟踪最后一项以及它是否匹配:
public int countBunches(int[] myArray)
{
int count = 0;
int lastItem;
boolean lastItemMatched;
for(int i = 0; i<myArray.length; i++)
{
if(i == 0)
{
lastItem = myArray[0];
lastItemMatched = false;
}
else
{
if(lastItem == myArray[i])
{
if(!lastItemMatched)
{
count++;
}
lastItemMatched = true;
} else {
lastItemMatched = false;
}
lastItem = myArray[i];
}
}
return count;
}
关于java - Java 数组中的一堆元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44102322/