How do a find the maximum non-repeating number in an integer array?

前端 未结 2 1496
青春惊慌失措
青春惊慌失措 2021-01-25 09:59

Suppose I have an unsorted integer array {3, -1, 4, 5, -3, 2, 5}, and I want to find the maximum non-repeating number (4 in this case) (5 being invalid as it is repeated). How c

2条回答
  •  醉酒成梦
    2021-01-25 10:18

    1. Sort the array in descending order.
    2. Begin from top element and store it a variable, say max.
    3. Check next element with max, if they are the same, repeat until you find the next max, otherwise, you found the max non-repeated number.

    Time complexity: O(nlogn)

    c++ implementation, based on my Sort (C++):

    #include 
    #include 
    #include 
    #include 
    #include 
    
    using namespace std;
    
    void printVector(vector& v)
    {
        for(vector::iterator it = v.begin() ; it != v.end() ; it++)
            cout << *it << ' ';
        cout << endl;
    }
    
    bool compar(const int& a, const int& b)
    {
        return (a > b) ? true : false;
    }
    
    
    int main()
    {
        vector v = {3, -1, 4, 5, -3, 2, 5};
        cout << "Before sorting : " << endl;
        printVector(v);
    
        sort(v.begin(), v.end(), compar);
    
        cout << endl << "After sorting : " << endl;
        printVector(v);
    
    
        int max_non_repeat = numeric_limits::min();
        for(unsigned int i = 0; i < v.size(); ++i)
        {
            if(max_non_repeat == v[i])
                max_non_repeat = numeric_limits::min();
            else if(v[i] > max_non_repeat)
                max_non_repeat = v[i];
        }
    
        cout << "Max non-repeated element: " << max_non_repeat << endl;
    
        return 0;
    }
    

    Output:

    C02QT2UBFVH6-lm:~ gsamaras$ g++ -Wall -std=c++0x  main.cpp 
    C02QT2UBFVH6-lm:~ gsamaras$ ./a.out 
    Before sorting : 
    3 -1 4 5 -3 2 5 
    
    After sorting : 
    5 5 4 3 2 -1 -3 
    Max non-repeated element: 4
    

    For maximum pleasure, do base your (a different) approach on How to find max. and min. in array using minimum comparisons? and modify it accordingly.

提交回复
热议问题