Find unique numbers in array

后端 未结 8 1142
被撕碎了的回忆
被撕碎了的回忆 2021-02-04 20:14

Well, I have to find how many different numbers are in an array.

For example if array is: 1 9 4 5 8 3 1 3 5

The output should be 6, because 1,9,4,5,8,3 are uniqu

8条回答
  •  独厮守ぢ
    2021-02-04 20:46

    Let me join the party ;)

    You could also use a hash-table:

    #include 
    #include 
    
    int main() {
    
        int a[] = { 1, 9, 4, 5, 8, 3, 1, 3, 5 };
        const size_t len = sizeof(a) / sizeof(a[0]);
    
        std::unordered_set s(a, a + len);
    
        std::cout << s.size() << std::endl;
        return EXIT_SUCCESS;
    
    }
    

    Not that it matters here, but this will likely have the best performance for large arrays.


    If the difference between smallest and greatest element is reasonably small, then you could do something even faster:

    • Create a vector that spans the range between min and max element (if you knew the array elements at compile-time, I'd suggest the std::bitset instead, but then you could just compute everything in the compile-time using template meta-programming anyway).
    • For each element of the input array, set the corresponding flag in vector.
    • Once you are done, simply count the number of trues in the vector.

提交回复
热议问题