java - How to remove all duplicates from an array -
i want remove every duplicate array in java , store remaining integers in same array.
e.g.: int[] = { 5,5,5,3,4,4,2,2,1}; ==> int[] = {3,1};
so far have tried using:
set<integer> set = new hashset<integer>(); (int = 0; < array.length; i++) { set.add(array[i]); } it appears though, removes 1 of duplicates , not both.
any appreciated.
you can use hashmap maintain count of each element , remove elements have count greater 1.
public int[] removeduplicates(int[] arr) { map<integer, integer> countmap = new linkedhashmap<>(); // maintain order (int n : arr) { integer count = countmap.get(n); if (count == null) { count = 0; } count++; countmap.put(n, count); } for(iterator<map.entry<string, string>> = countmap.entryset().iterator(); it.hasnext(); ) { map.entry<string, string> entry = it.next(); if (entry.getvalue() > 1) { it.remove(); } } return new arraylist<>(countmap.keyset()).toarray(new int[0]); }
Comments
Post a Comment