C++ O(n) time & O(n) space solution using unordered_set


  • 1
    Z

    class Solution {
    public:

    int thirdMax(vector<int>& nums) {
    
        int first = INT_MIN, second = INT_MIN, third = INT_MIN;
        unordered_set<int> dict;  // use unordered_set to record the counts of different numbers
        for(int i : nums) {
            dict.insert(i);
            if(i == first || i == second || i == third) continue;
            if(i > first) {
                third = second;
                second = first;
                first = i;
            } else if(i > second) {
                third = second;
                second = i;
            } else if(i >= third) {
                third = i;
            }
        }
        return dict.size() >= 3 ? third : first;
    }
    

    };


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.