LeetCode Third Maximum Number 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)的时间。 定义最大的数、第二大、第三大的数分别为first、second、third,遍历数组然后不断更新这三个数,更新的方法是从最大数错位赋值,很容易理解。求数组中第二大的数也是类似的道理。 看代码就很好理解了,注意数组中可能会有INT_MIN,所以需要用long数据类型。另外,本题要求的第三大是相异数字的排名,比如第三个样例,第三大的应该是1,而不是2,虽然有第二个2排名第三,但和第二名重复了,不能算,这一点在两个else if中需要保证严格小于第一名或第二名。 [cpp] class Solution { public: int thirdMax(vector<int>& nums) { long first = LONG_MIN, second = LONG_MIN, third = LONG_MIN; for (int i = 0; i < nums.size(); ++i) { if (nums[i] > first) { third = second; second = first; first = nums[i]; } else if (nums[i] < first && nums[i] > second) { third = second; second = nums[i]; } else if (nums[i] < second && nums[i] > third)third = nums[i]; } if (third == LONG_MIN)return first; else return third; } }; [/cpp] 本代码提交AC,用时6MS。]]>
Pingback: hihoCoder 1496-寻找最大值 | bitJoy > code