數組去重

Write a function to remove duplicated objects from an array. Preserve the order. For example, if the input array is [1, 5, 4, 2, 7, 2, 6, 5], the result should be [1, 5, 4, 2, 7, 6]. The implementation should be optimized for executing speed.

設計一個方法,能夠移除一個數組的重複元素,這裏給你一個整型數組,比如
[1, 5, 4, 2, 7, 2, 6, 5],裏面有2個5,2個2,移除重複元素後就是[1, 5, 4, 2, 7, 6],

我的方法是:
使用一個 LinkedHashSet 來存儲只出現一次的元素,第二次出現的時候,就忽略該元素,然後使用該LinkedHashSet來組成結果。

    public int[] removeDuplicated(int[] array) {

        LinkedHashSet<Integer> set = new LinkedHashSet<Integer>();

        int j = 0;

        for (int i : array) {

            set.add(i);

        }

        int[] result = new int[set.size()];

        Iterator<Integer> iterator = set.iterator();

        while (iterator.hasNext()) {

            result[j++] = iterator.next();

        }

        return result;

    }
發佈了88 篇原創文章 · 獲贊 5 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章