我正在寻找解决方案:
Given a array and a number P , find two numbers in array whose product equals P.
寻找比O(n * 2)更好的解决方案。我可以使用额外的空间或其他数据结构。感谢您的帮助吗?
答案 0 :(得分:24)
传递数组,并将元素添加到Hashtable。对于添加的每个元素x,检查H /中是否已存在P / x - 如果是,则x和P / x是您的解决方案之一。这将是你能得到的最佳效果。
答案 1 :(得分:10)
您可以尝试滑动窗口方法。首先对所有数字进行越来越多的排序,然后使用两个整数begin
和end
来索引当前的数字对。将begin
初始化为0,将end
初始化为最后一个位置。然后将v[begin]
和v[end]
的产品与P
:
begin
。end
。这是一个实现了这个想法的C ++代码。由于排序,此解决方案为O(n * log(n)),如果您可以假设数据已排序,则可以跳过O(n)解决方案的排序。
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);
}
答案 2 :(得分:3)
这个只适用于整数: 将P分解为素数的乘积。通过将这些分为两组,您可以获得将P作为产品的对。现在你只需要检查数组中是否存在它们,这就是哈希表非常有用的地方。此外,在创建哈希表时,您还可以过滤重复值数组,大于P的值,或者甚至是P中未包含素数因子的值。
答案 3 :(得分:0)
这是我的镜头,它只会将任何因素相互比较一次
P <- The Number
theArray <- new array[theData]
factors <- new array[]
isFactor <- new map(init: false)
factorCount <- 0
i <- 0
while i is in theArray
num <- theArray[i]
if (isFactor[num])
skip
if num modulo P == 0
isFactor[num] <- true
j <- 0
while j is in factors
if factors[j] * num == P
return (num, factors[j])
j++
factors.push(num)
factorCount++
i++
答案 4 :(得分:0)
1.在O(nlogn)时间内将数字分配到数组A中,删除任何零
2.创建一个数组B,使得O [n]时间内B [i] = P / A [I]
3.对于B中的每个B [k],在A中对该元素进行二进制搜索,在最坏的情况下采用O(nlogn)时间
如果元素B [k]存在于位置m的数组A中,那么A [k] * A [m] = P 否则不存在这样的一对
总运行时间为O(nlogn)
当然,由于浮点错误,这可能会在真机上遇到困难
答案 5 :(得分:0)
不确定这是否是最佳解决方案但是有效。你可以尝试优化它。
public class CombInput
{
public int ID;
public string Value;
}
public List<string> GetCombinations(List<string> values)
{
List<CombInput> input = new List<CombInput>();
List<string> outputvalues = new List<string>();
int counter = 1;
foreach (String c in values)
{
input.Add(new CombInput { ID = counter, Value = c });
counter++;
}
var Output = from i in input
select i;
string Final = Output.Select(query => query.Value).Aggregate((a, b) => a + "|" + b);
while (!Output.ToList().Exists(s=>s.Value.ToString()==Final))
{
var store = Output;
var Output1=
(from o in Output
from v in input
where (v.ID < o.ID && !(store.Any(a=>a.Value==v.Value + "|" + o.Value)))
select new CombInput { ID = v.ID, Value = v.Value + "|" + o.Value });
var Outputx = (from s in store select s)
.Concat
(from s in Output1.ToList() select s);
Output = Outputx;
}
foreach (var v in Output)
outputvalues.Add(v.Value);
return outputvalues.ToList();
}
public List<string> GetProductCombinations(List<int> nums, int productCriteria)
{
List<string> input = (from i in nums
select i.ToString()).ToList();
input = GetCombinations(input);
var O = from i in input
where i.Split('|').ToList().Select(x => Convert.ToInt32(x)).ToList().Aggregate((a, b) => a * b) == productCriteria
select i;
List<string> output=new List<string>();
foreach (string o in O)
{
output.Add(o);
}
return output;
}
private void button1_Click(object sender, EventArgs e)
{
List<string> output = new List<string>();
List<int> nums = new List<int>();
int[] numsarr ={1,2,3,4,6,7,8,12};
nums = numsarr.ToList();
output = GetProductCombinations(nums, 12);
}
答案 6 :(得分:0)
这个算法是O(n)
答案 7 :(得分:0)
void PrintPairOfProduct(int arr [],int size,int k) {
int i,temp[MAX];
memset(temp,1,MAX);
for(i=0;i<size;++i)
{
if(k % arr[i] == 0 && temp[arr[i]] != -1 && temp[k/arr[i]] != -1)
{
if((temp[k/arr[i]] * arr[i]) == k)
{
printf("Product of %d * %d = %d",k/arr[i],arr[i],k);``
temp[k/arr[i]] = -1;
temp[arr[i]] = -1;
}
temp[arr[i]] = arr[i];
}}
答案 8 :(得分:0)
以下可能是解决方案之一。我只是个新手。如果我的算法存在错误,请原谅我。
让输入数组为inputArr,并假设inputArr
中元素的值范围为>= 0, <= M
。
创建一个大小为M + 1的bool数组,即presenceOfInputValue,
并将其所有元素初始化为false。
找到值x后,inputArr
,presenceOfInputValue[x] = true
。
这意味着,如果输入数组中存在presenceOfInputValue[x] == true
,x
。
Let double Bi = p/arr[i].
循环获取所有Bi并设置presenceOfInputValue,如果Bi是一个整数,通过检查presenceOfInputValue[i] == true
来检查inputArr中是否存在。
P.S。假设M = 256^4(4bytes) - 1
,presenceOfInputValue将占用256^4/8/1000/1000 ~= 16.8MB
答案 9 :(得分:0)
public boolean factors_Of_Product_In_Array(int a[],int product,int factorsLimit)
{
int i = 0,count = 0;
boolean flag = false;
if(factorsLimit==0)
flag = false;
//If product value is zero - only verify if there is any '0' value in array
else if(product==0)
{
for(i=0;i<a.length;i++)
{
if(a[i]==0)
flag = true;
}
}
//If product value is 1 - Verify at least factorsLimit number of 1's should be present in array
else if(product==1)
{
for(i=0;i<a.length;i++)
{
if(a[i]==0)
count=count+1;
}
if(count==factorsLimit)//Verifying if the number of 1's is equal to number of factors required
flag = true;
}
else
{
for(i=0; i<a.length && count!=factorsLimit ;i++)
{
if(product%a[i]==0)
{
product = product/a[i];
count = count+1;
System.out.println(" "+a[i]+" ");
}
}
if(count==factorsLimit)
flag = true;
}
return flag;
}
答案 10 :(得分:-1)
#include<stdio.h>
int main()
{
int arr[]={2,15,4,5,6,7};
const int c = 30;
int i = 0,j=1;
int num =0;
while ( i<= 6 )
{
num = arr[i] * arr[j];
if ( num == 30)
{
printf("Pairs[%d,%d]\t",arr[i],arr[j]);
}
if (j == 5 )
{
i = i+1;
j = i + 1;
if (j==6)
{
break;
}
else
{
continue;
}
}
j= j+1;
}
return 0;
}