Array of unique elements?

后端 未结 5 2074
时光取名叫无心
时光取名叫无心 2020-12-06 05:52

Given an array like the one below, I was wondering if there is an easy way to turn this array into an array with unique values only?

This is given:

         


        
5条回答
  •  隐瞒了意图╮
    2020-12-06 06:32

    Here are 2 ideas:

    1. Add all items to a Set, or create one with the constructor that has an array as a parameter (HashSet or TreeSet, depending on what time complexity you want). Then, for each element in the set, remove it, adding it to the next open position of a new array that is the size of the set.

    2. Sort the array. Add the object at index 0 to an ArrayList. Start at index 1 and go to index length - 1. If the current element is not equal to the element at the previous index, add it to the ArrayList. Change the ArrayList into an array, if necessary.

提交回复
热议问题