使用java查找连续的数字

时间:2014-03-17 03:37:30

标签: java arrays

我正在开发一个比较数组的程序,我必须检查是否有任何连续的匹配。

例如,如果我有2个数组:

{3,4,2,5,6}第一个数组

{4,8,9,2,5}第二个数组

在这个例子中,我有3个连续的比赛,即4,2,5。

在第一个数组中,我们按顺序排列了4,2,5,它们位于第二个数组中。

示例2:

{3,4,6,5,2}第一个数组

{4,8,9,2,5}第二个数组

在这个中我只有2个连续的数字,分别为5和2。

5和2在第一个数组中按顺序排列,它们在第二个数组中。

public static boolean checkConsecutive(int[] firstArray,  int[] secondArray)
   {
      boolean consecutive = false;

      for(int i = 0; i < firstArray.length ; i++)
      {
         for (int j = 0; j < secondArray.length; j++)
         {
            if (firstArray[i] == secondArray[j])
               consecutive = true;
            else 
               consecutive = false;
         }
      }
      return consecutive; 

我怎么知道我有多少连续数字?

1 个答案:

答案 0 :(得分:0)

首先,你的算法是比较每个数组的最后一个元素,如果它们不相等则返回false,如果它们匹配则返回true。在循环中使用else条件会使您的算法错误,因为您将要连续覆盖,有时会将其更改为false,尽管它已经是真的。我只是假设你不想那样。

其次以算法的方式思考它:

For(i) each of the first array's elements, 
    for(j) each element of the second array after the last match, until you find a match
        if you find a match, increase a counter, stop the second loop

您必须控制循环第二个循环的方式,以便在第二个数组中仅计算每个元素一次。

我不知道自己是否已经清楚,但很难在没有为你解决问题的情况下提供线索。

相关问题