比O(n²)解决方案更快,可以将所有整数划分总结在数组上

发布于 2025-02-01 03:54:51 字数 365 浏览 5 评论 0原文

我被赋予了这个代码段作为作业。

int arr[n];
int sum = 0;
for (int i = 0; i < n; ++i) {
  for (int j = 0; j < n; ++j) {
   sum += arr[i] / arr[j];
  }
}

假设:N&LT; 10⁶,ARR中的所有元素均为INT类型,并且小于10⁶

我的任务是比O(n²)时间更快地返回总和。在过去的几个小时中,我一直在考虑这个问题,但我似乎找不到任何方法来加快速度(除了O((N²+n)/2),我可以通过对数字进行排序并分开来实现这一点而分子大于分母)。

I was given this snippet of code as an assignment.

int arr[n];
int sum = 0;
for (int i = 0; i < n; ++i) {
  for (int j = 0; j < n; ++j) {
   sum += arr[i] / arr[j];
  }
}

Assumptions: n < 10⁶, all elements in arr are of type int and are smaller than 10⁶

My task is to return sum faster than O(n²) time. I've been thinking about this for the past few hours and I can't seem to find any way to speed it up (apart from O((n²+n)/2) which I would achieve by sorting the numbers and dividing only while the numerator is larger than the denominator).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

清旖 2025-02-08 03:54:51

请为我们提供更多代码deatails

,顺便说一句,总的来说,您可以对O(nlogn)进行排序(合并,插入,插入等等),这将是更好的然后o((n²+n)/2)在运行时项。

please provide us more code deatails

And by the way , in general you can sort in O(nlogn) (merge sort,insertion sort and more) and that will be must better then O((n²+n)/2) in runtime terms.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文