如何将一个数组中的数据除重【高效率】

如何将一个数组中的数据除重【高效率】

1.循环遍历,去除重复

  • ArrayUtils类
package InAction;

import java.util.HashMap;

public class ArrayUtils {
    public static void reduceRepetionOne(int [] array){
        for(int i = 0; i< array.length;i++){
            for(int j = i+1;j < array.length;j++){//从i+1开始
                if(array[i] == array[j]){
                    array[j] = -1;//标识为-1
                }
            }
        }
    }


    private static HashMap<Integer, Integer> hashMap =
            new HashMap<Integer, Integer>();

    public static HashMap<Integer,Integer> reduceRepetionTwo(int []array){
        for(int i = 0;i< array.length;i++){
             if(!hashMap.containsKey(array[i])){
                 hashMap.put(array[i],1);
             }
        }
        return hashMap;
    }

    public static void printArray(int array[]){
        for(int j = 0;j < array.length;j++){//从i+1开始
            if(array[j] != -1){
                System.out.print(array[j]+" ");
            }
        }
    }
}
  • MapUtils类
package InAction;

import java.util.Iterator;
import java.util.Map;

public class MapUtils {
    //打印map的第一种方式
    public static void printMapOne(Map map){
        for(Object entry: map.keySet()){
            System.out.println("key :"+entry+",value :"+map.get(entry));
        }
    }

    //打印map的第二种方式[待完善]
    /*
    1.把这个Map中的键值对作为一个整体(Entry)放入Iterator中,然后遍历
     */
    public static void printMapTwo(Map map){
        Iterator<Map.Entry<Integer, Integer>> it = map.entrySet().iterator();

        while(it.hasNext()){
            Map.Entry<Integer, Integer> entry = it.next();
            System.out.println("key= "+entry.getKey()+
                    " and value= "+entry.getValue());
        }
    }

/*
3.打印map的第三种方式
*/
    public static void printMapThree(Map<Integer,Integer> map){
        for(Map.Entry<Integer, Integer> entry : map.entrySet()){
            System.out.println("key= "+entry.getKey()+" and value= "+entry.getValue());
        }
    }
}
  • Test类
package InAction;

import java.util.HashMap;
import java.util.Map;

public class Test {
    static int array[] = {1,2,3,1,4,2,2,5};
    public static void main(String[] args) {
        Map<Integer, Integer> hashMap = new HashMap<Integer, Integer>();
        hashMap = ArrayUtils.reduceRepetionTwo(array);
        MapUtils.printMapOne(hashMap);
    }
}

运行结果:

key :1,value :1
key :2,value :1
key :3,value :1
key :4,value :1
key :5,value :1
key= 1 and value= 1
key= 2 and value= 1
key= 3 and value= 1
key= 4 and value= 1
key= 5 and value= 1

Process finished with exit code 0

猜你喜欢

转载自blog.csdn.net/liu16659/article/details/80656637