Given a non-empty array of integers, return the third maximum number in this array. If it does not exist, return the maximum number. The time complexity must be in O(n).
Example 1:
Input: [3, 2, 1]
Output: 1
Explanation: The third maximum is 1.Example 2:
Input: [1, 2]
Output: 2
Explanation: The third maximum does not exist, so the maximum (2) is returned instead.Example 3:
Input: [2, 2, 3, 1]
Output: 1
Explanation: Note that the third maximum here means the third maximum distinct number. Both numbers with value 2 are both considered as second maximum. Runtime: 8 ms, faster than 85.71% of C++ online submissions for Third Maximum Number.
class Solution {
public:
int thirdMax(vector<int>& nums) {
int size = nums.size();
if (size < 2) {
return nums[0];
}
if (size < 3) {
return max(nums[0], nums[1]);
}
int nth = 0;
for (int i = 0; i < size; i++) {
int idx = size - i - 1;
for (int j = 0; j < idx; j++) {
if (nums[j + 1] < nums[j]) {
int temp = nums[j];
nums[j] = nums[j + 1];
nums[j + 1] = temp;
}
}
if (i == 0) {
nth++;
} else if (nums[idx] < nums[idx + 1]) {
nth++;
}
if (nth == 3) {
return nums[idx];
}
}
return nums[size - 1];
}
};