我在問是否可以優化此代碼。(第一個代碼)。我認為使用 getCommon 很復雜(第二個代碼),我不需要創建回圈來使用我的方法,有沒有簡單的方法在主類中使用 getCommon ?
public int [] getCommon(int [] array1, int [] array2) {
int length = array1.length < array2.length ? array1.length : array2.length; // choosing the shortest length.
int [] tempArray = new int [length]; // array to store common elements.
int counterNewArray = 0; // counter loop for tempArray.
for(int counter1 = 0; counter1 < array1.length; counter1 ) {
for(int counter2 = 0; counter2 < array2.length; counter2 ) {
if(array1[counter1] == array2[counter2]) {
tempArray = insertIndex(tempArray, counterNewArray, array1[counter1]); // insertIndex is another method i implemented before.
counterNewArray ;
break;
}
}
}
// the purpose of this array is to store only common elements, because tempArray holds zeros when there is no common element.
int [] newArray = new int [counterNewArray];
int tempLength = newArray.length - 1;
while(tempLength >= 0) newArray[tempLength] = tempArray[tempLength--];
return newArray;
}
主類包含
public class mainClass {
public static void main(String[] args) {
array arr = new array(); // I use my class here.
int [] num = {0,1,2,3,4,5,6,7,8,9,10};
int [] num1 = {4,6,4,3,6,5,8,5,5,5,10};
int [] newArray = arr.getCommon(num, num1);
for(int counter = 0; counter < newArray.length; counter ) System.out.println(newArray[counter]);
}
}
uj5u.com熱心網友回復:
例如具有流和 lambda 的解決方案,針對可讀性進行了優化
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
int[] array1 = {0,1,2,3,4,5,6,7,8,9,10};
int[] array2 = {4,6,4,3,6,5,8,5,5,5,10};
Arrays.stream(getCommon(array1, array2)).forEach(System.out::println);
}
public static int[] getCommon(int[] array1, int[] array2){
List<Integer> list1 = Arrays.stream(array1).boxed().collect(Collectors.toList());
List<Integer> list2 = Arrays.stream(array2).boxed().collect(Collectors.toList());
List<Integer> commonList = list1.stream().filter(list2::contains).collect(Collectors.toList());
return commonList.stream().mapToInt(Integer::intValue).toArray();
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/457937.html
下一篇:c 空模板函式回傳非空函式指標
