用純數(shù)組實現(xiàn)刪除指定元素,包括重復(fù)元素全部刪除

琢磨用數(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);
    }
}

參考地址:http://blog.csdn.net/love9099/article/details/62234013

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容