如何高效去除数组里重复数字,看完你就明白了

  • 题目描述: 给定一个整形数组,例如:21,23,25,15,15,23,98,5,21  去除重复项之后保留的数组为25,98,5.
  • java语言解法:
    public class ArrayViewUtils {
    
        /**
         * @desc  删除数组里重复的数字,只保留不重复的数字。
         * 时间复杂度分析为O(n)
         * @param arr 数组
         * @return arr[]
         */
        public static int[] delRepeatFromArray(int[] arr) {
            if(null==arr){
                return null;
            }
            int length = arr.length;
            if(length<1){
                return null;
            }
                //统计重复出现数字的总个数
            int repeatSum=0;
            HashMap map = new HashMap<>(length,1.0F);
            for (int i = 0; i 

     

  • 利用hashMap 的特性,一次循环,key则是数组里的数字,value记录数组里的数字出现的次数,大于1则重复出现。
  • 再一次循环数组,把不重复的数字记录到新的数组里。
  • 这里可以分析到时间复杂度为O(n),空间复杂度 新建里数组和map,复杂度也为O(n).

你可能感兴趣的:(算法)