【Leetcode】479. Second Max of Array

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;
    }
}
发布了42 篇原创文章 · 获赞 12 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/WBST5/article/details/105505127