Leetcode Third Maximum Number 414
来源:互联网 发布:pdf.js 无法显示字体 编辑:程序博客网 时间:2024/05/21 22:32
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; }};
0 0
- LeetCode #414: Third Maximum Number
- Leetcode Third Maximum Number 414
- [LeetCode]414 Third Maximum Number
- LeetCode 414 --- Third Maximum Number
- Leetcode 414:Third Maximum Number
- [LeetCode 414] Third Maximum Number
- Leetcode 414 Third Maximum Number
- LeetCode 414 Third Maximum Number
- LeetCode.414 Third Maximum Number
- LeetCode Third Maximum Number
- LeetCode-Third Maximum Number
- [Leetcode] Third Maximum Number
- LeetCode: Third Maximum Number
- leetcode---Third Maximum Number
- LeetCode : Third Maximum Number
- leetcode[Third Maximum Number]
- LeetCode Third Maximum Number
- leetCode-Third Maximum Number
- Android 项目 Android 学习手册(一)
- 微信小程序之二(创建文件目录)
- Lambda Architecture
- 寒假篇7——奖学金
- Apk脱壳圣战之---如何脱掉“梆梆加固”的保护壳
- Leetcode Third Maximum Number 414
- iOS界面布局的几种方式
- Handle、Looper与Message之间的关系
- iOS 中 常用的第三方库
- Hessian 2.0序列化协议规范
- 用sklearn和tensorflow做boston房价的回归计算的比较(2)--卷积神经网路CNN
- iOS获取手机信息
- sql server 查询去掉重复记录
- 文件系统中打开某指定类型文件时,关联并用自己的APP打开