返回介绍

solution / 0400-0499 / 0414.Third Maximum Number / README_EN

发布于 2024-06-17 01:04:00 字数 3765 浏览 0 评论 0 收藏 0

414. Third Maximum Number

中文文档

Description

Given an integer array nums, return _the third distinct maximum number in this array. If the third maximum does not exist, return the maximum number_.

 

Example 1:

Input: nums = [3,2,1]
Output: 1
Explanation:
The first distinct maximum is 3.
The second distinct maximum is 2.
The third distinct maximum is 1.

Example 2:

Input: nums = [1,2]
Output: 2
Explanation:
The first distinct maximum is 2.
The second distinct maximum is 1.
The third distinct maximum does not exist, so the maximum (2) is returned instead.

Example 3:

Input: nums = [2,2,3,1]
Output: 1
Explanation:
The first distinct maximum is 3.
The second distinct maximum is 2 (both 2's are counted together since they have the same value).
The third distinct maximum is 1.

 

Constraints:

  • 1 <= nums.length <= 104
  • -231 <= nums[i] <= 231 - 1

 

Follow up: Can you find an O(n) solution?

Solutions

Solution 1

class Solution:
  def thirdMax(self, nums: List[int]) -> int:
    m1 = m2 = m3 = -inf
    for num in nums:
      if num in [m1, m2, m3]:
        continue
      if num > m1:
        m3, m2, m1 = m2, m1, num
      elif num > m2:
        m3, m2 = m2, num
      elif num > m3:
        m3 = num
    return m3 if m3 != -inf else m1
class Solution {
  public int thirdMax(int[] nums) {
    long m1 = Long.MIN_VALUE;
    long m2 = Long.MIN_VALUE;
    long m3 = Long.MIN_VALUE;
    for (int num : nums) {
      if (num == m1 || num == m2 || num == m3) {
        continue;
      }
      if (num > m1) {
        m3 = m2;
        m2 = m1;
        m1 = num;
      } else if (num > m2) {
        m3 = m2;
        m2 = num;
      } else if (num > m3) {
        m3 = num;
      }
    }
    return (int) (m3 != Long.MIN_VALUE ? m3 : m1);
  }
}
class Solution {
public:
  int thirdMax(vector<int>& nums) {
    long m1 = LONG_MIN, m2 = LONG_MIN, m3 = LONG_MIN;
    for (int num : nums) {
      if (num == m1 || num == m2 || num == m3) continue;
      if (num > m1) {
        m3 = m2;
        m2 = m1;
        m1 = num;
      } else if (num > m2) {
        m3 = m2;
        m2 = num;
      } else if (num > m3) {
        m3 = num;
      }
    }
    return (int) (m3 != LONG_MIN ? m3 : m1);
  }
};
func thirdMax(nums []int) int {
  m1, m2, m3 := math.MinInt64, math.MinInt64, math.MinInt64
  for _, num := range nums {
    if num == m1 || num == m2 || num == m3 {
      continue
    }
    if num > m1 {
      m3, m2, m1 = m2, m1, num
    } else if num > m2 {
      m3, m2 = m2, num
    } else if num > m3 {
      m3 = num
    }
  }
  if m3 != math.MinInt64 {
    return m3
  }
  return m1
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文