我正在制作一些用于查找某个数的素因子的方法.这被分解为两个使用数组的函数.但是,在这两个函数中,代码效率非常低.首先,我必须计算数组的长度,创建一个具有该长度的新数组,然后使用几乎完全相同的代码来填充数组.
有没有一种方法可以使数组未知宽度并将整数推送到数组的末尾,因为我找到它们?
这是我的代码:
public class JavaApplication7{
public static void main(String[] args) {
System.out.println(Arrays.toString(primeFactors(85251)));
}
public static int[] primeFactors(int num){
int[] factors = primesUpTo(num);
int originalNum = num;
int i = 0;
int count = 0;
while(num != 1){
if(num % factors[i] == 0){
num /= factors[i];
i = 0;
count++;
}else{
i++;
}
}
int[] primeFactors = new int[count];
i = 0;
count = 0;
while(originalNum != 1){
if(originalNum % factors[i] == 0){
originalNum /= factors[i];
primeFactors[count] = factors[i];
i = 0;
count++;
}else{
i++;
}
}
return primeFactors;
}
public static int[] primesUpTo(int upTo){
int count = 0;
int num = 2;
while(num <= upTo){
boolean isPrime = true;
for(int div = 2; div <= num / 2; div++){
isPrime = num % div == 0 ? false : isPrime;
}
count += isPrime ? 1 : 0;
num++;
}
int i = 0;
num = 2;
int[] primes = new int[count];
while(num <= upTo){
boolean isPrime = true;
for(int div = 2; div <= num / 2; div++){
isPrime = num % div == 0 ? false : isPrime;
}
if(isPrime){
primes[i] = num;
i++;
}
num++;
}
return primes;
}
}
解决方法:
你可以使用比Arrays更动态的Arraylists.
However in both functions the code is very inefficient as first i have
to count the length of the array, make a new array of that length and
then use almost the exact same code to populate the array
然而,你会发现Arraylists确实看起来很动态,但在它们下面却做了类似的事情.它们以一个大小开始,并将基础数组的副本复制到更大的数组等.
如果你知道要存储多少个数字的上限,你可以做的另一件事就是实现你自己的容器类.它可以有一个大数组来保存数字和一个长度变量,用于循环遍历元素.
例如:
public class NumberContainer(){
private int[] elements;
private int numOfElements;
public NumberContainer(int size){
elements = new int[size];
numOfElements = 0;
}
//add a number
public void add(int x){
elements[numOfElements] = x;
numOfElements++;
}
//get length
public int length(){
return numOfElements;
}
}
….等等.
这样,您不必将数组复制到新的大数组,总而言之,假设您实例化具有足够大的NumberContainer.
希望这可以帮助
标签:java,arrays,performance,repeat
来源: https://codeday.me/bug/20190830/1768782.html