using vector as priority_queue, ugly solution


  • 0
    X
    bool compare(const int& a, const int& b) {
      return a > b;
    }
    
    class Solution {
    public:
      int thirdMax(vector<int>& nums) {
        vector<int> minHeap;
        for (auto n: nums) {
          bool breakFlag = false;
          for (auto num: minHeap) {
            if (num == n) {
              breakFlag = true; break;
            }
          }
          
          if (breakFlag) continue;
          
          if (minHeap.size() < 3 || n > minHeap[0]) {
              minHeap.push_back(n);
              push_heap(minHeap.begin(), minHeap.end(), compare);
              if (minHeap.size() > 3) {
                  pop_heap(minHeap.begin(), minHeap.end(), compare);
                  minHeap.pop_back();
              }
          }
        }
        
        if (minHeap.size() == 3) return minHeap[0];
        int maxValue = INT_MIN;
        for (auto n: minHeap) maxValue = max(n, maxValue);
        return maxValue;
      }
    };
    
    
    

    '''


Log in to reply
 

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