Leetcode Third Maximum Number 414
阿新 • • 發佈:2019-02-20
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.
找到第三大的數字 時間複雜度是O(n)
考慮遍歷三次:
但是會出現,其中出現最小數的情況,然後程式碼就跟別人不一樣了。。。。
我考慮標記位置來紀錄,因為位置不能是負數
class Solution {
public:
int thirdMax(vector <int>& nums) {
int len=nums.size();
int maxnum=nums[0];
int maxpos=0;
for(int i=0;i<len;i++){
if(maxnum<nums[i]) {
maxnum=nums[i];
maxpos=i;
}
}
int second=INT_MIN;
int secpos=-1 ;
for(int i=0;i<len;i++){
if(nums[i]==maxnum) continue;
if(second<=nums[i]) {
second=nums[i];
secpos=i;
}
}
if(second==INT_MIN && secpos==-1) {
return maxnum;
}
int third=INT_MIN;
int thpos=-1;
for(int i=0;i<len;i++){
if(nums[i]==maxnum || nums[i]==second) continue;
if(third<=nums[i]) {
third=nums[i];
thpos=i;
}
}
return (third==INT_MIN && thpos==-1) ? maxnum:third;
}
};
程式碼有點長,學習別人的:
class Solution {
public:
int thirdMax(vector<int>& nums) {
long first = LONG_MIN, second = LONG_MIN, third = LONG_MIN;
for (int num : nums) {
if (num > first) {
third = second;
second = first;
first = num;
} else if (num > second && num < first) {
third = second;
second = num;
} else if (num > third && num < second) {
third = num;
}
}
return (third == LONG_MIN || third == second) ? first : third;
}
};