NicholasAdamou

Problem 2: Show all unique elements in an integer array

Sep 13th, 2019
304
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.45 KB | None | 0 0
  1. import java.util.*;
  2.  
  3. public class Main {
  4.     // Given a sorted array of integers, write a function to print the unique numbers in the array.
  5.     // EXPECTED OUTPUT: 12, 13, 14, 17, 21, 33, 43, 55, 61, 77, 900
  6.     public static void main(String[] args) {
  7.         int array[] = { 12, 13, 14,14, 17, 21, 33,43, 43, 43, 55, 61, 77, 900 };
  8.  
  9.         System.out.println("EXPECTED OUTPUT: [12, 13, 14, 17, 21, 33, 43, 55, 61, 77, 900]");
  10.         printDistinct(array);
  11.     }
  12.  
  13.     // Simplest solution is to use a HashMap because the HashMap data structure only stores a unique
  14.     // key-value pair for each element it contains, with no duplicates.
  15.     private static void printDistinct(int array[]) {
  16.         // Create the HashMap data structure holding two integers
  17.         HashMap<Integer, Integer> hashMap = new HashMap<>();
  18.  
  19.         // Loop over the length of the array of integers and place
  20.         // each element into the HashMap.
  21.         for (int i = 0; i < array.length; i++) {
  22.             hashMap.put(array[i], i);
  23.         }
  24.  
  25.         // Sort the keys of the HashMap by placing all keys into a ArrayList.
  26.  
  27.         // Create the ArrayList Structure that has the length of the HashMap.
  28.         List<Integer> sortedKeys = new ArrayList<>(hashMap.size());
  29.         // Add all the keys to the ArrayList.
  30.         sortedKeys.addAll(hashMap.keySet());
  31.         // Sort all the keys in the ArrayList in ascending order.
  32.         Collections.sort(sortedKeys);
  33.  
  34.         // Print out the keys of the HashMap, since all keys are unique.
  35.         System.out.println("ACTUAL OUTPUT: " + sortedKeys);
  36.     }
  37. }
Add Comment
Please, Sign In to add comment