【发布时间】:2020-03-09 02:33:32
【问题描述】:
对于目前困扰我的问题,我应该编写一个名为 countTriples 的静态方法,它将任何 int 数组作为参数和一个整数键,并返回三个或更多连续键的次数出现。超过三个键的序列仍然算作一个三元组。
伪代码示例:countTriples([1 3 3 3 0 3 3 1 3 3 3 8], 3) => 2
伪代码示例:countTriples([1 7 7 7 0 7 7 7 7 1 7 7 7 7 7 8], 7) => 3
伪代码示例:countTriples([1 14 14 4 1 14], 14) => 0
这是我目前所拥有的,它适用于某些情况,但不适用于以下情况:{1,2,1,1,1,5,6,7,8,1,1,1,1}
import java.util.*;
public class Sample {
public static int countTriples(int[] data, int key) {
int count = 0;
int c= 0;
for (int i = 0; i < data.length-1; i++) {
if (data[i] == key) {
c++;
if (c >= 3) {
count++;
c = 0;
}
}
else {
count = 0;
}
}
System.out.println(count);
return count;
}
public static void main(String[] args) {
int[] arr = {1,2,1,1,1,5,6,7,8,1,1,1,1};
countTriples(arr, 1);//currently returns 1, 2 expected
}
}
感谢任何帮助
【问题讨论】:
-
在数组中:
[1 7 7 7 0 7 7 7 7 1 7 7 7 7 7 8],不会7 7 7 7实际上算作 2 和 `7 7 7 7 7` 算作 3?这将提供总共 6,而不是 3。还是我错了? -
想知道同样的事情^
-
超过三个键的序列仍然算作一个三倍,但是是的,这是我第一次遇到的问题,因为它重叠
-
key代表什么?您要查找的号码?
-
是的,它代表您正在寻找的数字的“团块”
标签: java