LintCode: Second Max of Array

Second Max of Array



Similar Problems:


Description

Find the second max number in a given array.

You can assume the array contains at least two numbers.

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

Given [1, 2], return 1.

Github: code.dennyzhang.com

Credits To: lintcode.com

Leave me comments, if you have better ways to solve.


  • Solution:
// Blog link: https://code.dennyzhang.com/second-max-of-array
// Basic Ideas: Manually implement a minheap with 2 items
// Complexity: Time O(n), Space O(1)
/**
 * @param nums: An integer array
 * @return: The second max number in the array.
 */
func secondMax (nums []int) int {
    l := make([]int, 2)
    for i, num := range nums {
        if i == 0 {
            l[0] = num
        } else {
            if i == 1 {
                if num <= l[0] {
                    l[1] = num
                } else {
                    l[0], l[1] = num, l[0]
                }
            } else {
                if num >= l[0] {
                    l[0], l[1] = num, l[0]
                } else {
                    if num > l[1] { l[1] = num }
                }
            }
        }
    }
    return l[1]
}
linkedin
github
slack

Share It, If You Like It.

Leave a Reply

Your email address will not be published.