我应该编写一个程序来读取整数数组并输出数组中"三元组"的数量。
"三元组"是三个连续的整数,递增顺序相差 1(即 3,4,5 是三元组,但 5,4,3 和 2,4,6 不是(。
如何检查"三元组"?
当前代码:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
// put your code here
Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt();
int[] array = new int[size];
int iterator = 0;
for(int i = 0; i < size; i++){
array[i] = scanner.nextInt();
} for(int j =0; j < size; j++){
iterator++;
}
}
}
以下代码循环遍历整个整数数组。在循环内部检查数组((i + 2) < array.Length
(中是否存在第三个整数,其他2个条件都是关于value1是否与值2减少1(array[i] == array[i + 1] - 1
和array[i + 1] == array[i + 2] - 1
for (int i = 0; i < array.Length; i++)
{
if((i + 2) < array.Length && array[i] == array[i + 1] - 1 && array[i + 1] == array[i + 2] - 1)
System.out.println("Three values at indexes" + i + " " + (i + 1) + " and " + (i + 2) + " are a triple");
}
下面的代码是 C#,遗憾的是与 Java 不兼容,我将把它留给任何想知道它在 C# 中如何处理的人(vt
变量是所谓的ValueTriple
(:
(int, int, int) vt;
for (var i = 0; i < array.Length; i++)
{
if (i + 2 >= array.Length) continue;
vt = (array[i], array[i + 1], array[i + 2]);
if (vt.Item1 == vt.Item2 - 1 && vt.Item2 == vt.Item3 - 1)
Console.WriteLine($"Three values at indexes {i}, {i + 1} and {i + 2} (Values: {array[i]}, {array[i + 1]}, {array[i + 2]}) are a triple");
}
您可以尝试以下代码
import java.util.Scanner;
public class Triplet {
public static void main(String[] args) {
// put your code here
Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt();
int[] array = new int[size];
for(int i = 0; i < size; i++){
array[i] = scanner.nextInt();
}
Integer counter = 0;
for(int i = 0; i < size-2; i++) {
if(array[i] == array[i+1] - 1 && array[i] == array[i+2] - 2) { //checking if three consecutive ints in increasing order differing by 1
counter++;
}
}
System.out.println(counter);
}
}
希望这会有所帮助。
找出三胞胎数量的方法可能如下所示。然后,您只需根据输入的获取方式调用该方法,并希望呈现结果。
public static int getNumberOfTriplets(int[] toBeChecked) {
int numberOfTriplets = 0;
int nextIndex = 0;
while (nextIndex < toBeChecked.length - 2) {
int first = toBeChecked[nextIndex];
int second = toBeChecked[nextIndex + 1];
int third = toBeChecked[nextIndex + 2];
if ((first + 1 == second) && (second + 1 == third)) {
numberOfTriplets++;
}
nextIndex++;
}
return numberOfTriplets;
}
尽管允许数字在多个三元组中,答案在我个人如何处理它方面非常相似:
//determines if the input sequence is consecutive
public boolean isConsecutive(int... values) {
return IntStream.range(1, values.length)
.allMatch(i -> values[i] == values[i - 1] + 1);
}
public int countTriples(int[] input, boolean uniques) {
if (input.length < 3) {
return 0;
}
int back = 0;
for(int i = 2; i < input.length; i++) {
if (isConsecutive(input[i - 2], input[i - 1], input [i]) {
back++;
if (uniques) { //whether to disallow overlapping numbers
i += 2; //triple found, ignore the used numbers if needed
}
}
}
return back;
}
然后在调用它时:
Int[] input = new int[] {1, 2, 3, 5, 6, 7, 8};
countTriples(input, true); //3
countTriples(input, false); //2