数组

Java数组去重问题

2017-10-28  本文已影响0人  修之竹

方法一:

使用两个标志位进行标定去重。此方法无需使用任何容器,也不需要另外开辟数组空间,推荐使用,但丢失了数组元素之间的位置信息。
public static void solution(int[] array){
        //先排序
        Arrays.sort(array);
        //然后用两个标志位进行标定去重
        int p=0,q=0;
        for(int i = 0; i < array.length-1; ++i){
            if(array[i] != array[i + 1]){
                if(p < q){
                    array[p+1] = array[q+1];
                    p++;q++;
                }else{
                    p = i + 1;
                }
            }else{
                q = i + 1;
            }
        }
        //将去重之后的数组输出
        for(int i = 0; i <= p; ++i){
            System.out.print(array[i] + " ");
        }
        System.out.println("length = " + (p+1));
    }

方法二:

使用Java中的Set容器进行去重。使用方便,但依赖Set容器。

不用事先排好序,利用Set容器中元素不能重复的特性,但也丢失了数组元素之间的位置信息。

        Set set = new HashSet<>();
        for(int i = 0; i < array.length; ++i){
            set.add(array[i]);
        }
        //将不重复的元素返回给原始数组
        int m = 0;
        for(Iterator iterator = set.iterator(); iterator.hasNext();){
            array[m] = (int)iterator.next();
            m++;
        }
        //输出查看结果
        for(int j = 0; j < set.size(); ++j){
            System.out.print(array[j] + " ");
        }
        System.out.println();
        System.out.println("length = " + set.size());

方法三:

使用Java中的List容器进行去重。使用方便,但依赖List容器。

也不用事先排好序,可用contains方法判断list中有无这个元素,无则add进去,有则跳过,这样可以保留原始数组元素之间的相对位置信息。

        List list = new ArrayList<>();
        for(int i = 0; i < array.length; ++i){
            if(!list.contains(array[i]))
                list.add(array[i]);
        }
        //将不重复的元素返回给原始数组
        for(int i = 0; i < list.size(); ++i){
            array[i] = (int)list.get(i);
        }
        //输出查看结果
        for(int i = 0; i < list.size(); ++i){
            System.out.print(array[i] + " ");
        }
        System.out.println();
        System.out.println("length = " + list.size());

欢迎探讨~

上一篇 下一篇

猜你喜欢

热点阅读