How do I get a unique number in array

Viewed 141
number = {5,3,5,5,5,6,6,9,3,3};

How do I get a unique number which is not duplicated in array?

What I want to get

9

My code is below

int[] list = {5,3,5,5,5,6,6,9,3,3};
Arrays.sort(list);
for(int i = 0; i < list.length; i++){
        for(int j = i+1; j < list.length; j++){
                if(list[i] == list[j]){
                        break;
                }
        }
}
4 Answers

This is a brute force approach but can solve you problem.

public static int GetUnique(int val){
    int count = 0;
    int[] list = {5,3,5,5,5,6,6,9,3,3};
    for(int i = 0; i < list.length; i++){
        for(int j = i+1; j < list.length; j++){
            if(list[i] == list[j]){
                count++;
        }
    }
    if(count == 1)
        return list[i];
    count = 0;
        }
        return 0
    }

Efficient way of finding non repeating elements from given array would be by using hash tables:

Construct a hash table consisting of element and it's occurrence count by traversing the given array

Map<Integer, Integer> hashTable = new HashMap<>();
    for(int i = 0; i < list.length; i++) {
        if(hashTable.containsKey(list[i])) {
            hashTable.put(list[i], hashTable.get(list[i]) + 1);
        } else {
            hashTable.put(list[i], 1);
        }
    }

Once the hash table is ready, then any desired operations on it can be performed. For example: If first non repeating number is to be found, then a simple iteration on the given list would suffice:

for(int i = 0; i < list.length; i++) {
            if(hashTable.get(list[i]) == 1) {
                System.out.println(list[i]);
                break;
            }
        }

Time complexity of this approach is O(n)

You can also use Java Stream API:

Integer[] list = {5,3,5,5,5,6,6,9,3,3,13};
Map<Integer, Long> counts = Arrays.stream(list)
               .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
int[] uniqueValues = counts.entrySet().stream().filter(e -> e.getValue().equals(1L)).mapToInt(Map.Entry::getKey).toArray();

Output:

[9, 13]

This is what happened:

  1. First, numbers have been grouped by occurrences in format: number: occurrences of number:
3:  3 occurrences
5:  4 occurrences
6:  2 occurrences
9:  1 occurrence
13: 1 occurrence
  1. In next step we filter above groups by leaving only numbers with 1 occurrence and mapping result into final array

If list[i-1] != list[i] and list[i]!=list[i+1] Then, it's necessary to manage start and end of the array, otherwise arrayIndexOutOfBoundsException raise.

    int[] list = {3,3,5,6,6,9,9,15};
Arrays.sort(list);

for(int i = 0; i <list.length; i++){


    
        if( (i==0 && (list[i]!=list[i+1])) || ((i>0) && (list[i]!=list[i-1]) && (( i==list.length-1) || (list[i+1]!=list[i]))) ){
            System.out.println(list[i]);
            break;
        }
}
Related