Lintcode: 數組第二大數

問題:

在數組中找到第二大的數

樣例:

例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;
    }
};

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章