【问题标题】:Interview Q: Finding mode of array [duplicate]采访Q:数组的查找方式[重复]
【发布时间】:2014-11-15 19:51:01
【问题描述】:

我最近在面试,面试官问了我以下问题:

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?

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

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

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

我不知道如何回答这个问题,他把这个留给我作为以后的练习。已经好几天了,我还是不知道该怎么做。

谁能知道怎么做?>

【问题讨论】:

  • 如何在常量内存中对数组进行排序?恒定内存意味着无法移动项目。您要么必须制作副本并对副本进行排序,要么使用指针数组并按其目标值对指针数组进行排序。
  • +1 for the f word sorry 必须是:-)
  • @ThomasMatthews 当有人说排序算法使用恒定数量的内存时,这意味着该算法引入了恒定的内存开销,但显然存储数组是 O(n)。也就是说,您如何比较快速排序和合并排序?众所周知,快速排序使用 O(1) 内存,而归并排序使用 O(n),因此使用 O(1) 内存(有相关定义)对数组进行排序绝对是可能的
  • 不幸的是,除非宇宙的大小(最大 int 大小)被认为是恒定的,否则这可能无法完成。如果是,您可以使用此处给出的解决方案:stackoverflow.com/questions/11781720/…
  • @Dici:要求说constant memory,我理解是只读内存或者内存中的值不能更改。

标签: java c++ arrays algorithm


【解决方案1】:

如果数字在合理范围内,您可以使用具有值范围大小的数组线性计算众数。

数组中的值将是 mode 数组的索引。增加值。保留其他两个频率最高的变量和频率最高的值的索引。

#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&lt;/*value*/, /*frequency*/&gt;

这个算法不是常数时间,而是O(N)或者更少。

【讨论】:

  • 那么这和user3735521的hashmap方案不一样吗?
  • 不,略有不同。我没有使用hash。我的理解是哈希是将函数应用于索引值的结果,我没有这样做。
猜你喜欢
  • 2014-08-22
  • 1970-01-01
  • 1970-01-01
  • 2012-09-25
  • 2018-04-19
  • 2013-07-31
  • 1970-01-01
  • 2016-08-15
  • 2016-06-23
相关资源
最近更新 更多