问题:
在数组中找到第二大的数
样例:
例1:
输入:[1,3,2,4], 输出:3。
例2:
输入:[1,2], 输出:1。
注意事项
你可以假定至少有两个数字
python:
class Solution:
"""
@param nums: An integer array
@return: The second max number in the array.
"""
def secondMax(self, nums):
# write your code here
maxNum = max(nums[0], nums[1])
secNum = min(nums[0], nums[1])
if len(nums) > 2:
for i in range(2, len(nums)):
if nums[i] > secNum:
if nums[i] > maxNum:
secNum = maxNum
maxNum = nums[i]
else:
secNum = nums[i]
return secNum
C++:
class Solution {
public:
/**
* @param nums: An integer array
* @return: The second max number in the array.
*/
int secondMax(vector<int> &nums) {
// write your code here
int maxNum = max(nums[0], nums[1]);
int secNum = min(nums[0], nums[1]);
if(nums.size() > 2)
{
for(int i = 2; i < nums.size(); i++)
{
if(nums[i] > secNum)
{
if(nums[i] > maxNum)
{
secNum = maxNum;
maxNum = nums[i];
}else{
secNum = nums[i];
}
}
}
}
return secNum;
}
};