美文网首页
用纯数组实现删除指定元素,包括重复元素全部删除

用纯数组实现删除指定元素,包括重复元素全部删除

作者: KavinDotG | 来源:发表于2017-08-29 17:44 被阅读0次

琢磨用数组实现一个删除,琢磨了好几个小时都没成功,从网上找到的例子
问题瓶颈在于存放新数组的索引设置问题,其实设置初始值再自增即可。

public static int[] popSmallest(Integer[] arr, Integer num){
        int count = 0; //记录重复数据,用于计算新数组长度
        for(int i = 0 ; i<arr.length ; i++){  
            if(arr[i] == num){  
                count++;  
            }  
        }  
        int[] temp = new int[arr.length-count]; //用于存储新数据的数组
        //temp的索引
        int tempIndex  = 0 ;
        //把非num数据存储到新数组中。  
        for(int i = 0; i < arr.length ; i++){  
            if(arr[i] != num){  
                temp[tempIndex] = arr[i];  
              //一开始总是想新数组的索引要用for循环嵌套,其实只要给初始值自增即可
                tempIndex++; 
            }  
        }  
        return temp;  
    }


//入口函数
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

相关文章

网友评论

      本文标题:用纯数组实现删除指定元素,包括重复元素全部删除

      本文链接:https://www.haomeiwen.com/subject/blcadxtx.html