给定一个数p,发现数组,其产品的两个元素= P

编程入门 行业动态 更新时间:2024-10-11 21:23:02
本文介绍了给定一个数p,发现数组,其产品的两个元素= P的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我要寻找的解决方案:

Given a array and a number P , find two numbers in array whose product equals P.

寻找比O解决方案更好的(N * 2)。我没关系使用额外的空间或其他数据结构。任何帮助是AP preciated?

Looking for solution better than O(n*2) . I am okay with using extra space or other datastructure .Any help is appreciated ?

推荐答案

您可以尝试滑窗的方法。首先排序所有的数字越来越多,然后用两个整数开始和结束指数目前对数字。初始化开始 0和结束到最后的位置。然后比较 v [开始] 和 v [结束] 与 P :

You can try a sliding window approach. First sort all the numbers increasingly, and then use two integers begin and end to index the current pair of numbers. Initialize begin to 0 and end to the last position. Then compare the product of v[begin] and v[end] with P:

  • 如果是平等的,你找到了答案。
  • 如果是较低的,你必须找到一个更大的产品,移动开始前进。
  • 如果是更高的,你必须找到一个更小的产品,移动结束落后。
  • If it is equal, you found the answer.
  • If it is lower, you must find a bigger product, move begin forward.
  • If it is higher, you must find a smaller product, move end backward.

下面是一个C ++ code这个想法实现。该解决方案是O,因为排序(N *的log(n)),如果你可以假设数据进行排序,那么你可以跳过一个O排序(N)解决方案。

Here is a C++ code with this idea implemented. This solution is O(n*log(n)) because of the sorting, if you can assume the data is sorted then you can skip the sorting for an O(n) solution.

pair<int, int> GetProductPair(vector<int>& v, int P) { sort(v.begin(), v.end()); int begin = 0, end = static_cast<int>(v.size()) - 1; while (begin < end) { const int prod = v[begin] * v[end]; if (prod == P) return make_pair(begin, end); if (prod < P) ++begin; else --end; } return make_pair(-1, -1); }

更多推荐

给定一个数p,发现数组,其产品的两个元素= P

本文发布于:2023-11-29 10:17:11,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1646114.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   个数   元素   两个   发现

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!