【发布时间】:2017-02-18 15:10:49
【问题描述】:
我创建了这个算法,它所做的就是找到具有相同乘积的整数对,并且对中的整数必须不同。产品不得超过1024。这是我能想到的最简单的方法,有没有办法可以提高这个算法的效率和时间复杂度?
谢谢
import java.util.ArrayList;
public class Pairs {
public static void main(String [] args){
int nums[] = new int[1024];
for(int i = 1;i<=1024;i++){
nums[i-1] = i;
}
findPairs(nums);
}
static void findPairs(int [] nums){
ArrayList<IntPair> pairs = new ArrayList<IntPair>();
ArrayList<Products> products = new ArrayList<Products>();
IntPair tempObject;
Products tempProduct;
int tempMultiplication = 0;
for(int i =0;i<nums.length;i++){
for(int j=0;j<nums.length;j++){
tempObject = new IntPair(nums[i],nums[j]);
pairs.add(tempObject);
}
}
for(IntPair p:pairs){
tempProduct = new Products(p.x,p.y);
if(tempProduct.product <= 1024){
products.add(tempProduct);
}
}
for(int i = 0;i<products.size();i++){
tempMultiplication = products.get(i).product;
for(int j = 0;j<products.size();j++){
if(products.get(j).product == tempMultiplication)
{
if(products.get(i).x == products.get(j).x || products.get(i).y == products.get(j).y) {
}
else if (products.get(i).x == products.get(j).y || products.get(j).x == products.get(j).y || products.get(i).x == products.get(i).y){
}
else{
System.out.println("Matching pair found:("+ products.get(i).x + ","+products.get(i).y+")" + "("+ products.get(j).x + ","+products.get(j).y+")" );
}
}
}
}
}
}
【问题讨论】:
-
将所有(不同的)整数配对,将它们放入
Map<Integer, List<Pair>>,其中键是产品,值是与该产品的配对列表。 -
这里有很多需要改进的地方。使用 set/map 可以避免大量迭代(另请注意 j=0 应该是 j=i+1)
-
你无法提高最坏情况的时间复杂度:如果你正在寻找成对的东西,它至少必须是
O(n^2)。你所能做的就是减少乘法常数。 -
所以基本上我创建的这个算法没有那么糟糕吧?
-
@Jack 你能解释一下为什么我需要使用 j = i+1 而不是 j = 0 吗?谢谢你的回答
标签: java algorithm time complexity-theory