-2

我需要编写一个名为 Continuous 的方法,该方法接受 6 个参数来检查 6 个输入是否是连续数字,而不管顺序如何。如果数字是连续的,则返回 true,否则返回 false。有人可以教我什么是最有效的方法吗?我尝试了这种方法,但如果我有 6 个数字,它会效率低下吗?

public static boolean consecutive(int numberOne,int numberTwo,int numberThree) {
    if(((numberTwo==numberOne-1) && (numberThree== numberTwo-1)) || ((numberTwo==numberOne+1) && (numberThree==numberTwo+1)) || ((numberTwo==numberOne+2) &&( numberThree==numberOne+1)) || ((numberTwo==numberOne-1)&& (numberThree==numberOne+1)) || ((numberTwo==numberOne-2) && (numberThree==numberOne-1)) ||((numberTwo==numberOne+1) && (numberThree==numberOne-1))){
        return true;
    }else{
        return false;
    }
}

}
4

2 回答 2

10

将值添加到数组中,对数组进行排序,然后测试一组连续的值:

int[] test = new int[] {numberOne, numberTwo, etc...};
Arrays.sort(test);
for (int i = 0; i < test.length - 1; i++) {
  if (test[i] + 1 != test[i + 1]) {
    // Not sequential
  }
}
于 2013-03-05T12:11:30.250 回答
1

假设没有重复的数字,增强@Chris 的答案:

public static boolean consecutive(
  int numberOne,int numberTwo,int numberThree, 
  int numberFour, int numberFive, int numberSix) {

 int [] ns = { 
   numberOne, numberTwo, numberThree, 
   numberFour, numberFive, numberSix };

 Arrays.sort(ns);

 return ( ns[ns.length-1] - ns[0] == ns.length-1 );
}
于 2013-03-05T12:32:44.240 回答