C++ 3-line solution simply using set<int>

  • 0

    The STL set<int> would be the perfect container for this problem since it requires ordering with distinct values. Simply maintaining a set<int> with maximum size of 3 will give you O(N) solution.

        int thirdMax(vector<int>& nums) {
          set<int> top3;
          for (int x:nums) if (top3.insert(x), top3.size() > 3) top3.erase(top3.begin());
          return top3.size() == 3? *top3.begin() : *top3.rbegin();

Log in to reply

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