Given an integer array nums, return the third distinct maximum number in this array. If the third maximum does not exist, return the maximum number.
Example 1:
1 2 3 4 5 6
Input: nums = [3,2,1] Output: 1 Explanation: The first distinct maximum is 3. The second distinct maximum is 2. The third distinct maximum is 1.
Example 2:
1 2 3 4 5 6
Input: nums = [1,2] Output: 2 Explanation: The first distinct maximum is 2. The second distinct maximum is 1. The third distinct maximum does not exist, so the maximum (2) is returned instead.
Example 3:
1 2 3 4 5 6
Input: nums = [2,2,3,1] Output: 1 Explanation: The first distinct maximum is 3. The second distinct maximum is 2 (both 2's are counted together since they have the same value). The third distinct maximum is 1.
排序:
时间复杂度:O(nlogn)
空间复杂度:O(logn)
1 2 3 4 5 6 7 8 9 10 11 12
classSolution { public: intthirdMax(vector<int> &nums){ sort(nums.begin(), nums.end(), greater<>()); for (int i = 1, diff = 1; i < nums.size(); ++i) { if (nums[i] != nums[i - 1] && ++diff == 3) { return nums[i]; } } return nums[0]; } };
classSolution { public: intthirdMax(vector<int> &nums){ long a = LONG_MIN, b = LONG_MIN, c = LONG_MIN; for (long num : nums) { if (num > a) { c = b; b = a; a = num; } elseif (a > num && num > b) { c = b; b = num; } elseif (b > num && num > c) { c = num; } } return c == LONG_MIN ? a : c; } };
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
classSolution { public: intthirdMax(vector<int> &nums){ int *a = nullptr, *b = nullptr, *c = nullptr; for (int &num : nums) { if (a == nullptr || num > *a) { c = b; b = a; a = # } elseif (*a > num && (b == nullptr || num > *b)) { c = b; b = # } elseif (b != nullptr && *b > num && (c == nullptr || num > *c)) { c = # } } return c == nullptr ? *a : *c; } };