Search code examples
c++arrayssortinguniquemin

How can I find minimum and unique element of array in c++?


I have array(of numbers) with size N. I need to find minimum element which is unique,so if arr[5] ={1,2,3,1,2}, answer is 3. I tried that with following code:

Int n = sizeof(arr)/sizeof(arr[0]);
sort(arr,arr + n);
for(int i = 0;i<N;i++){
     for(int j = 0;j<N;j++){
        if(arr[i] == arr[j]){
           remove(arr,arr+n,i);
           remove(arr,arr+n,j);
        }
    }
}

But problem is that this only work if I have 2 identical elements of arr.I could create if conditions for number of identical, but I can have 3 or 4 or 1000,so it will be pretty odd. So what is more elagant way to do this? Thank you in advance.


Solution

  • try this code, this uses an unordered map

    int m = 2147483647;
        int int_array[] = { 1,2,3,3,1,6,7,7,9 };
        unordered_map<int, int> map;
        for (int i = 0; i < sizeof(int_array) / sizeof(int_array[0]); i++) {
            map[int_array[i]] = map[int_array[i]] + 1;
        }
        unordered_map<int, int>::iterator itr;
    
        for (itr = map.begin(); itr != map.end(); itr++)
        {
            if (itr->second == 1) {
                if (itr->first < m) {
                    m = itr->first;
                }
            }
        }
        printf("minimum unique is %d", m);