414. Third Maximum Number
来源:互联网 发布:企业数据安全 编辑:程序博客网 时间:2024/05/12 01:38
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: 1Explanation: The third maximum is 1.
Example 2:
Input: [1, 2]Output: 2Explanation: The third maximum does not exist, so the maximum (2) is returned instead.
Example 3:
Input: [2, 2, 3, 1]Output: 1Explanation: Note that the third maximum here means the third maximum distinct number.Both numbers with value 2 are both considered as second maximum.
用三个变量,分别记录最大值,第二大值和第三大值,在一次遍历过程中不断更新。还有,注意处理边界值-2147483648。
class Solution {public: int thirdMax(vector<int>& nums) { int firstMax = -2147483648; int secondMax = -2147483648; int thirdMax = -2147483648; int i; int count = 0; bool flag = false; for(i = 0; i < nums.size(); i ++){ if(firstMax < nums[i]){ thirdMax = secondMax; secondMax = firstMax; firstMax = nums[i]; count ++; }else if(secondMax < nums[i] && firstMax != nums[i]){ thirdMax = secondMax; secondMax = nums[i]; count ++; }else if(thirdMax < nums[i] && firstMax != nums[i] && secondMax != nums[i]){ thirdMax = nums[i]; count ++; }else if(nums[i] == -2147483648 && count < 3 && !flag){ count ++; flag = true; } } if(count >= 3) return thirdMax; return firstMax; }};
0 0
- 414. Third Maximum Number
- 414. Third Maximum Number
- 414. Third Maximum Number
- 414. Third Maximum Number
- 414. Third Maximum Number
- 414. Third Maximum Number
- 414. Third Maximum Number
- 414. Third Maximum Number
- 414. Third Maximum Number
- 414. Third Maximum Number
- 414. Third Maximum Number
- 414. Third Maximum Number
- 414. Third Maximum Number
- 414. Third Maximum Number
- 414. Third Maximum Number
- 414. Third Maximum Number*
- 414. Third Maximum Number
- 414. Third Maximum Number
- Unity 相机的移动旋转以及拉近拉远的原理
- 数据库的数据模型
- 3无效列类型报错
- Unix进程
- hdu1010 Tempter of the Bone(dfs)
- 414. Third Maximum Number
- Mysql数据库表分区深入详解
- MATLAB 函数 mesh()用法
- windows下安装numpy+mtk,scipy,python_speech_features
- 搭建git服务器——小组级别
- Unity3D - 导航网格自动寻路(Navigation Mesh)
- el表达式
- 二叉树的遍历与深度和节点数的计算代码实现
- 安卓NDK开发-实现图片的高效压缩