琢磨用數(shù)組實現(xiàn)一個刪除,琢磨了好幾個小時都沒成功,從網(wǎng)上找到的例子
問題瓶頸在于存放新數(shù)組的索引設(shè)置問題,其實設(shè)置初始值再自增即可。
public static int[] popSmallest(Integer[] arr, Integer num){
int count = 0; //記錄重復(fù)數(shù)據(jù),用于計算新數(shù)組長度
for(int i = 0 ; i<arr.length ; i++){
if(arr[i] == num){
count++;
}
}
int[] temp = new int[arr.length-count]; //用于存儲新數(shù)據(jù)的數(shù)組
//temp的索引
int tempIndex = 0 ;
//把非num數(shù)據(jù)存儲到新數(shù)組中。
for(int i = 0; i < arr.length ; i++){
if(arr[i] != num){
temp[tempIndex] = arr[i];
//一開始總是想新數(shù)組的索引要用for循環(huán)嵌套,其實只要給初始值自增即可
tempIndex++;
}
}
return temp;
}
//入口函數(shù)
public static void main(String[] args) {
Integer[] test = {3,5,6,11,3,4,6,12,3,4,5};
for(int j : SelectSort.popSmallest(test, 3)){
System.out.println(j);
}
}