LeetCode-414. 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.
Example 2:
Input: [1, 2]

Output: 2

Explanation: The third maximum does not exist, so the maximum (2) is returned instead.
Example 3:
Input: [2, 2, 3, 1]

Output: 1

Explanation: Note that the third maximum here means the third maximum distinct number.
Both numbers with value 2 are both considered as second maximum.

func thirdMax(_ nums: [Int]) -> Int {
    var nums = nums.sorted()
    var tmp = 2
    var max = 0
    for i in (0..<nums.count).reversed() {
        if i-1 >= 0 && nums[i-1] < nums[i] {
            tmp -= 1
            if tmp == 0 {
                max = nums[i-1]
            }
        }
    }
    return tmp <= 0 ? max : nums[nums.count-1]
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 原题是: Given a non-empty array of integers, return the thir...
    小双2510阅读 156评论 0 0
  • 前言 本来this应该放在《上下文环境和作用域》中来讲,结果发现自己整理的时候,例子越来越多,所以单独写一篇用于加...
    cduyzh阅读 449评论 0 0
  • 曲回婉转 歌以成章 三日不绝 缥缈绕梁 宫商角变 徵羽成乐 秋风萧瑟 木叶飘落 转轴拨弦 错以成诗 司马青衫 沦落...
    翟诚然阅读 236评论 0 0
  • 嘻嘻 终于忙完工作躺尸啦 决定写篇不正经不专业的健身干货分享给你们呀! 其实 断断续续健身也有四年啦~起初想减肥 ...
    甜茶甜茶我最甜阅读 332评论 6 2