Java:如何计算整数数组中非重复元素的数量?

时间:2016-02-14 16:49:32

标签: java arrays int duplicates

你如何只计算两个阵列中的一个中的数字

示例:countdifference([2,4,4,4,4,6,6,8],[3,4,6,6,9])返回4因为4和6是重复的,剩下的数字是2 ,8,3和9。

noOfRepeatsCount方法旨在考虑arrayB中的重复元素:即6

我得到一个超出范围的索引数组异常:-1为noOfRepeatsCount方法。有什么想法吗?

public class countNonRepeated {

  static int countDifference(int[] arrayA, int[] arrayB) {
    int count = 0, repeatCount = 0, noOfRepeatsCount = 0;
    /*
    int noOfRepeats = 0;
    for (int k = 0; k < arrayB.length; k++) {
      if (arrayB[k] == arrayB[k - 1]) {
        noOfRepeats++;
      } else {
        continue;
      }
    */

    for (int i = 0; i < arrayA.length; i++) {
      for (int j = 0; j < arrayB.length; j++) {
        if (arrayA[i] == arrayB[j]) {
          if (arrayA[i + 1] == arrayB[j]) {
            repeatCount++;
          } else {
            count++;
          }
        } else {
          continue;
        }
      }
    }
    int length = arrayA.length + arrayB.length;
    return length - (noOfRepeatsCount * repeatCount) - (count * 2);
  }

  static int noOfRepeatsCount(int[] arrayB) {
    int noOfRepeats = 0;
    for (int k = 0; k < arrayB.length; k++) {
      if (arrayB[k] == arrayB[k - 1]) {
        noOfRepeats++;
      } else {
        continue;
      }
    }
    return noOfRepeats;
  }

  public static void main(String args[]) {
    int arrayA[] = { 2, 4, 4, 4, 4, 6, 6, 8 };
    int arrayB[] = { 3, 4, 6, 6, 9 };
    // System.out.println(noOfRepeatsCount(arrayA));
    System.out.println(countDifference(arrayA, arrayB));
  }
}

2 个答案:

答案 0 :(得分:0)

请参阅noOfRepeatsCount方法中的for循环。 if (arrayB[k] == arrayB[k - 1])发生异常错误。由于初始k值为0,因此您可以访问arrayB[-1]

如果您想解决此问题,请将for (int k = 0; k < arrayB.length; k++)更改为for (int k = 1; k < arrayB.length; k++)

答案 1 :(得分:0)

如何将数组转换为Sets并使用removeAll(),addAll()和size()的组合来获得所需的结果。我想这会使算法更清晰,避免出现一个错误。

我现在没时间发布代码示例,抱歉。

相关问题