JrPtn
JrPtn

Reputation: 83

Java: Unique Items in an array

I can't seem to wrap my brain around this, but lets say I'm given an array with different elements in it. If I wanted to create another array with only the unique elements from the first array, how would I go about doing that without using Maps, HashSets etc (without importing anything else from java).

Upvotes: 0

Views: 1183

Answers (2)

user166390
user166390

Reputation:

Please don't up-vote this, see Cratylus's answer - or better, harpun's comment. This is just some "pseudocode" for a solution with O(n2) complexity.


foreach element1 in array:
    duplicate = false
    foreach element2 in array:
        if element 1 == element 2:
            duplicate = true
            break // out of inner loop
    if duplicate:
       // duplicate
    else:
       // not duplicate

Of course this can be more cleanly expressed at a slightly higher level. The definition of "contains" should be evident.

foreach element in array:
   if contains(array, element):
       // duplicate

Upvotes: 0

Cratylus
Cratylus

Reputation: 54074

Simple brute force algorithm.
Just (double) loop over the array and check if is element is repeated or not. If not add it to the array and continue. O(N^2) complexity instead of O(N) complexity using a Map or Set

Upvotes: 3

Related Questions