Advertisement
gelita

Return only unique ints in an array

Feb 8th, 2020
245
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 0.98 KB | None | 0 0
  1.  
  2. import java.io.*;
  3. import java.util.*;
  4.  
  5. class MyCode {
  6.  
  7.   /**
  8.    * 1
  9.    * Unique
  10.    *
  11.    * Given an array of integers, return an array with all duplicates removed.*
  12.    *
  13.    * Parameters
  14.    * Input: arr {Array of Integers}
  15.    * Output: {ArrayList of Integers}
  16.    *
  17.    * Constraints
  18.    *
  19.    * Time: O(N)
  20.    * Space: O(N)
  21.    *
  22.    * Examples
  23.    * [1, 2, 4, 4, 5, 6] --> [1, 2, 4, 5, 6]
  24.    * [1, 1, 2, 2, 3, 3]' --> [1, 2, 3]
  25.    * [1, 2, 3, 1, 2] --> [1, 2, 3]
  26.    */
  27.  
  28.   public static void main (String[] args) {
  29.         int[]arr = new int[]{1, 2, 3, 1, 2};
  30.     //ArrayList<Integer> resultsList = new ArrayList<Integer>();
  31.     //resultsList = unique(arr);
  32.     System.out.println(unique(arr));
  33.    
  34.     }
  35.  
  36.    public static ArrayList<Integer> unique(int[] arr) {
  37.       HashSet<Integer> set = new HashSet<Integer>();
  38.       for(int i = 0; i<arr.length; i++){
  39.         set.add(arr[i]);
  40.       }
  41.       ArrayList<Integer> list = new ArrayList<Integer>(set);
  42.       return list;
  43.    }
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement