NicholasAdamou icon

Problem 2: Show all unique elements in an integer array

NicholasAdamou | PRO | 09/13/19 10:57:36 PM UTC | 0 ⭐ | 209 👁️ | Never ⏰ | []
Java |

1.45 KB

|

None

|

0 👍

/

0 👎

import java.util.*;
 
public class Main {
    // Given a sorted array of integers, write a function to print the unique numbers in the array.
    // EXPECTED OUTPUT: 12, 13, 14, 17, 21, 33, 43, 55, 61, 77, 900
    public static void main(String[] args) {
        int array[] = { 12, 13, 14,14, 17, 21, 33,43, 43, 43, 55, 61, 77, 900 };
 
        System.out.println("EXPECTED OUTPUT: [12, 13, 14, 17, 21, 33, 43, 55, 61, 77, 900]");
        printDistinct(array);
    }
 
    // Simplest solution is to use a HashMap because the HashMap data structure only stores a unique
    // key-value pair for each element it contains, with no duplicates.
    private static void printDistinct(int array[]) {
        // Create the HashMap data structure holding two integers
        HashMap<Integer, Integer> hashMap = new HashMap<>();
 
        // Loop over the length of the array of integers and place
        // each element into the HashMap.
        for (int i = 0; i < array.length; i++) {
            hashMap.put(array[i], i);
        }
 
        // Sort the keys of the HashMap by placing all keys into a ArrayList.
 
        // Create the ArrayList Structure that has the length of the HashMap.
        List<Integer> sortedKeys = new ArrayList<>(hashMap.size());
        // Add all the keys to the ArrayList.
        sortedKeys.addAll(hashMap.keySet());
        // Sort all the keys in the ArrayList in ascending order.
        Collections.sort(sortedKeys);
 
        // Print out the keys of the HashMap, since all keys are unique.
        System.out.println("ACTUAL OUTPUT: " + sortedKeys);
    }
}

Comments