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.
自己的笨方法, 粗暴, 易理解, 且符合题目要求:
使用了set.
扫描三遍数组:
第一遍: 找出max, 并依次把每个元素送入set, 若 set.size() < 3, 返回max;
第二遍找出sec, 第三遍找出third;
返回 third.
(O(n)) time, (O(n)) extra space.
int thirdMax(vector<int>& A) {
int i, n = A.size();
int max = INT_MIN, sec = INT_MIN, third = INT_MIN;
set<int> set;
for (i = 0; i < n; i++) {
set.insert(A[i]);
max = max > A[i] ? max : A[i];
}
if (set.size() < 3) return max;
for (i = 0; i < n; i++)
if (A[i] != max)
sec = sec > A[i] ? sec : A[i];
for (i = 0; i < n; i++)
if (A[i] != max && A[i] != sec)
third = third > A[i] ? third : A[i];
return third;
}
人家的精巧方法:
用到set, set.erase(), set.begin(), set.rbegin()
set 默认升序. set.rbegin()
表示最后一个元素的迭代器(指针).
(O(n)) time, (O(n)) extra space.
int thirdMax(vector<int>& A) {
set<int> top3;
for (int i = 0; i < A.size(); i++) {
top3.insert(A[i]);
// set 默认按 key 升序排序
if (top3.size() > 3) top3.erase(top3.begin());
}
return top3.size() == 3 ? *top3.begin() : *top3.rbegin();
}