采访问:寻找阵列的模式

时间:2014-11-15 19:51:02

标签: java c++ arrays algorithm

我最近在接受采访时,面试官问我以下问题:

Given an unsorted array, how do you calculate the mode in O(N)?

我回答了使用散列图,O(N)循环数组和O(1)查找的问题。

然后他说

If you had to use constant memory but were allowed more processor time, how would you do it?

我回答'排序数组并找到最长的运行,运行时= O(nlgn)

他问的下一个问题搞砸了我..

If you had to use constant memory and linear time how would you do it?

我不知道怎么回答这个问题,他把这个留给我作为以后练习。已经好几天了,我仍然不知道怎么做。

有谁知道该怎么做?>

1 个答案:

答案 0 :(得分:0)

如果数字在合理范围内,则使用具有值范围大小的数组线性计算模式。

数组中的值将是模式数组的索引。增加价值。保留两个频率最高的变量和频率最高的值的索引。

#include <stdio>

int main(void)
{
  unsigned int frequencies[11] = {0}; // Assume range 1..10, inclusive.
  const unsigned int values[] =
    {1, 8, 4, 8, 7, 3, 2, 8, 5};
  const unsigned int value_quantity =  
    sizeof(values) / sizeof(values[0]);
  unsigned int greatest_frequency = 0;
  unsigned int value_of_greatest_frequency = 0;

  for (unsigned int i = 0; i < value_quantity; ++i)
  {
    // Calculate new frequency.
    const unsigned int frequency_index = values[i];
    ++frequencies[frequency_index];

    // Update "running" variables
    if (frequencies[frequency_index] > greatest_frequency)
    {
      greatest_frequency = frequencies[frequency_index];
      value_of_greatest_frequency = frequency_index;
    }
  }
  std::cout << "Mode is " << value_of_greatest_frequency
            << ", with frequency of " << greatest_frequency
            << "\n";
  return 0;
}

一遍,很多变数。这仅在值的范围合理时才有效。

另一个建议是使用std::map</*value*/, /*frequency*/>

此算法不是常量时间,而是O(N)或更少。