美文网首页
【Leetcode】479. Second Max of Arr

【Leetcode】479. Second Max of Arr

作者: 随时学丫 | 来源:发表于2018-06-30 15:22 被阅读35次

479. Second Max of Array

Find the second max number in a given array.

Notice

You can assume the array contains at least two numbers.

Example

Given [1, 3, 2, 4], return 3.

Given [1, 2], return 1.

思路:从数组前两位找到 first大 和 second 大的,从 i=2 开始遍历,不断找当前 first 大和 second 大,因此是O(n)

public class Solution {
    /**
     * @param nums: An integer array.
     * @return: The second max number in the array.
     */
    public int secondMax(int[] nums) {
        int first=Math.max(nums[0],nums[1]);
        int second=Math.min(nums[0],nums[1]);
        
        for(int i=2;i<nums.length;i++){
            if(nums[i]>first){
                second=first;
                first=nums[i];
            }else if(nums[i]>second){
                second=nums[i];
            }
        }
        return second;
    }
}

相关文章

网友评论

      本文标题:【Leetcode】479. Second Max of Arr

      本文链接:https://www.haomeiwen.com/subject/cpituftx.html