Leetcode - Height Checker
Leetcode - Angle Between Hands of a Clock

Leetcode - Third Maximum Number

violet posted @ Jul 14, 2020 08:43:09 AM in 算法 with tags Algorithm Golang array , 289 阅读

https://leetcode.com/problems/third-maximum-number/

Given a non-empty array of integers, return the third maximum number in this array. If it does not exist, return the maximum number. The time complexity must be in O(n).

Example 1:

Input: [3, 2, 1]

Output: 1

Explanation: The third maximum is 1.

 

func thirdMax(nums []int) int {
	if len(nums) == 1 {
		return nums[0]
	}
	if len(nums) == 2 {
		if nums[0] > nums[1] {
			return nums[0]
		}
		return nums[1]
	}

	first := math.MinInt64
	second := math.MinInt64
	third := math.MinInt64

	for i := 0; i < len(nums); i++ {
		if nums[i] == first || nums[i] == second || nums[i] == third {
			continue
		}
		if first == math.MinInt32 || nums[i] > first {
			third = second
			second = first
			first = nums[i]
		} else if second == math.MinInt32 || nums[i] > second {
			third = second
			second = nums[i]
		} else if third == math.MinInt32 || nums[i] > third {
			third = nums[i]
		}
	}

	fmt.Println("first: ", first)
	fmt.Println("second: ", second)
	fmt.Println("third: ", third)

	if third == math.MinInt64 {
		return first
	}
	return third
}

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter