It's too difficult for me to write it correct


  • 0
    F

    Here's my solution, use insert sort:

    class Solution {
    public:
        int thirdMax(vector<int>& nums) {
            int a[3] = {0}, diff = 0;
            a[0] = a[1] = a[2] = INT_MIN;
            bool contains_min = false;
            for (int i = 0; i < nums.size(); i++) {
                if (nums[i] == INT_MIN) contains_min = true;
                if (a[0] == nums[i] || a[1] == nums[i] || a[2] == nums[i]) continue;
                int mi = 0;
                if (nums[i] > a[mi]) {
                    while (nums[i] > a[mi + 1] && mi < 2) {
                        a[mi] = a[mi + 1];
                        ++mi;
                    }
                    a[mi] = nums[i];
                }
                ++diff;
            }
            if (contains_min) ++diff;
            if (diff < 3) return a[2];
            else return a[0];
        }
    };
    

    or we can use heap here.


Log in to reply
 

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