forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Rename arithmetic-slices.cpp to third-maximum-number.cpp
- Loading branch information
Showing
1 changed file
with
30 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
// Time: O(n) | ||
// Space: O(1) | ||
|
||
class Solution { | ||
public: | ||
int thirdMax(vector<int>& nums) { | ||
int count = 0; | ||
vector<int> top(3, numeric_limits<int>::min()); | ||
for (const auto& num : nums) { | ||
if (num > top[0]) { | ||
top[2] = top[1]; | ||
top[1] = top[0]; | ||
top[0] = num; | ||
++count; | ||
} else if (num != top[0] && num > top[1]) { | ||
top[2] = top[1]; | ||
top[1] = num; | ||
++count; | ||
} else if (num != top[0] && num != top[1] && num >= top[2]) { | ||
top[2] = num; | ||
++count; | ||
} | ||
} | ||
|
||
if (count < 3) { | ||
return top[0]; | ||
} | ||
return top[2]; | ||
} | ||
}; |