C ++函数查找数组的模式

时间:2019-06-30 01:02:11

标签: c++ data-structures

我正在尝试编码以找到整数数组的模式。 但是,通过尝试某些情况,我发现它会返回第二种模式。 非常感谢您帮助我找出代码逻辑中的错误。

例如,如果我们的数组为{3,3,3,2,2,1},它将返回2而不是1。

long mode(long *arr, int n) {
  int number = arr[0];
  int mode = number;
  int count = 1;
  int countMode = 1;

  for (int i = 1; i < n; i++) {
    if (*(arr + i) == number) { // count occurrences of the current number
      ++count;
    } else { // now this is a different number
      if (count > countMode) {
        countMode = count; // mode is the biggest ocurrences
        mode = number;
      }
      count = 1; // reset count for the new number
      number = *(arr + i);
    }
  }
  return mode;
}

0 个答案:

没有答案