私はこのアルゴリズムを作成しました。これは、同じ製品を持ち、ペアの整数が異なる必要がある整数のペアを見つけることです。製品は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>'に入れます。ここで、キーはプロダクトであり、値はそのプロダクトのペアのリストです。 –
ここで改善すべき点はたくさんあります。 set/mapを使うと、たくさんの繰り返しを避けることができます(j = 0はj = i + 1でなければなりません)。 – Jack
最悪の場合の時間の複雑さを改善することはできません。少なくとも 'O(n^2)'になるようにしてください。乗法定数を減らすだけです。 –