java输出包含一个或多个元素的整数数组
我的要求是:
- longestStreak:布尔数组->;整数
- 目的:计算最长的连续条纹的长度
- 输入参数值中出现的true
- 输入:值是长度至少为1的非空布尔数组
- 输出:输出在中找到的最大连续True数
- 输入数组
这就是我目前所做的:
public class Problem{
public static int[] longestStreak(boolean[] values) {
int [] returnValues = new int[1];
//when streakCounter has a value of 0, we are trying to find a new streak
int streakCounter = 0,
//
longestStreakFound = 0;
for(int boolCounter = 0; boolCounter < values.length; boolCounter++){
//if true increment streakCounter
if (values [boolCounter]){
//if starting a new streak, store index to the end of returnValues
if(streakCounter == 0){
//method name would be growArrayAndCopyValuesFromOriginal
int[] tempValues = new int[returnValues.length + 1];
for(int originalValueCounter = 0; originalValueCounter < returnValues.length; originalValueCounter++ ){
tempValues[originalValueCounter] = returnValues [originalValueCounter];
}
//originalValueCounter is not available in this scope
//System.out.println(originalValueCounter);
returnValues = tempValues;
//end growArrayAndCopyValuesFromOriginal method
returnValues [returnValues.length-1] = boolCounter;
}
streakCounter++;
}
else{//if false do...
if (longestStreakFound < streakCounter){
longestStreakFound = streakCounter;
}
streakCounter = 0;
}
}
returnValues[0] = longestStreakFound;
return returnValues;
}
/**
* This main method is a test for the longestStreak method.
* In the future it would be best to place this into a test class.
*/
public static void main(String[] args){
boolean[] bools = new boolean[]{true, true, true, false, true, true, true, true, true, false, true};
System.out.print("Longest streak found: " + longestStreak(bools));
}
}
预期结果:[2,0,3,8]
实际结果:[2,0,3,6,8]
有人能帮我找出我做错了什么吗
# 1 楼答案
这是我的解决方案:
循环检查从
false
到true
的“上升边”,并将位置保存在tmp
对象中,然后开始计算True的数量,并将其存储在tmp
对象中当“边”从
true
下降到false
时tmp
对象存储在resultMap
中,出现次数作为键如果已经有一个对象与相同数量的引用相关联,只需将引用索引附加到现有对象的数组中即可
TreeMap
按键自动对其内容排序。因此,最大真实数的结果出现在地图的最后一个元素中true, false, true, true
的输出是: