[英]Finding number of pairs in array where A[i] * A[j] > A[i] + A[j]
For eg if Array A is 例如,如果数组A是
A[0] = 0.1
A[1] = 0.6
A[2] = 1.2
A[3] = 1.7
A[4] = 3.5
then for pair (3,4) we have A[3]*A[4] > A[3]+A[4]
那么对于(3,4)对,我们有
A[3]*A[4] > A[3]+A[4]
I want to find the number of such pairs in an array. 我想在数组中查找此类对的数量。
Also A[i] = A1 [i] + A2[i]/1,000,000
同样,
A[i] = A1 [i] + A2[i]/1,000,000
Where A1 and A2 are inputs given and A1 and A2 are in sorted order . 其中A1和A2是给定的输入,而A1和A2是按排序的顺序 。
Answering with O(n^2) algorithm is trivial. 用O(n ^ 2)算法回答很简单。 I am told there is O(n) solution for this without using extra space.
有人告诉我有O(n)解决方案,无需使用额外的空间。 I am looking for that.
我在找那个。
x * y > x + y
divide by x*y (for positive values) 除以x * y(对于正值)
1/x + 1/y < 1
Let's the first cursor (R) points to the right element (minimal 1/a[i] value), and the second cursor (L) points to the left element. 让我们第一个光标(R)指向右边的元素(最小1 / a [i]值),第二个光标(L)指向左边的元素。
Move L to the right until sum of reciprocals reaches 1. 向右移动L,直到倒数之和达到1。
Add (RL) to result. 将(RL)添加到结果中。
Step R to left. 步骤R向左。
Repeat moving L, until R and L meet each other 重复移动L,直到R和L彼此相遇
Both cursors move at most N steps, so algorithm takes O(N) 两个光标最多移动N步,因此算法需要O(N)
As this was not clearly stated in the question I will make the following two assumptions in the following: 由于这个问题并未明确说明,因此我将在下面做出以下两个假设:
Both assumptions can be changed with small variations of the code. 两种假设都可以随代码的细微变化而更改。
A
is sorted because A1
and A2
are sorted. A
原因是分类A1
和A2
进行排序。 For a small example this looks like the following 作为一个小例子,如下所示
#include <iostream>
#include <vector>
using namespace std;
int main()
{
std::vector<double> A({0.1,0.15,0.25,0.29,0.35,0.55,0.65,0.85,1.15,1.44,1.46,1.59,1.88,2.01,2.04,2.05,3.01});
size_t i=0, j=A.size()-1;
int result = 0;
if (A[j] <= 2) return 0;
while (i != j) {
if (A[i]*A[j]>A[i]+A[j]) {
result += j-i;
cout << A[i] << " to " << A[j] << " for a total of " << result << endl;
--j;
} else {
++i;
}
}
return 0;
}
outputs 8. http://ideone.com/LaV9Cy 输出8. http://ideone.com/LaV9Cy
This is O(n)
and works because A[i+1] > A[i]
, thus (A[i+1] - 1) * (A[j] - 1) > (A[i] - 1) * (A[j] - 1) > 1
if the second >
holds. 这是
O(n)
并起作用,因为A[i+1] > A[i]
,因此(A[i+1] - 1) * (A[j] - 1) > (A[i] - 1) * (A[j] - 1) > 1
如果第二个>
成立。 We can therefore simply add the number of elements between the two extremals that we found ( result += ji;
) instead of trying all of them individually. 因此,我们可以简单地将找到的两个极值之间的元素数量相加(
result += ji;
),而不必单独尝试所有元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.