LeetCode414. Third Maximum Number

文章目录

一、题目

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?

二、题解

class Solution {
   
public:
    int thirdMax(vector<int>& nums) {
   
        set<int> s;
        for(auto x:nums){
   
            s.insert(x);
            if(s.size() > 3) s.erase(s.begin());
        }
        return s.size() == 3 ? *s.begin() : *s.rbegin();
    }
};

相关推荐

  1. LeetCode414. Third Maximum Number

    2023-12-28 23:18:06       56 阅读
  2. leetcode414-Third Maximum Number

    2023-12-28 23:18:06       33 阅读
  3. leetcode 494.目标和

    2023-12-28 23:18:06       43 阅读
  4. Leetcode 412. Fizz Buzz

    2023-12-28 23:18:06       39 阅读
  5. LeetCode 494. 目标和

    2023-12-28 23:18:06       32 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2023-12-28 23:18:06       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2023-12-28 23:18:06       106 阅读
  3. 在Django里面运行非项目文件

    2023-12-28 23:18:06       87 阅读
  4. Python语言-面向对象

    2023-12-28 23:18:06       96 阅读

热门阅读

  1. 关于与Flask配套的Jinja2的使用

    2023-12-28 23:18:06       57 阅读
  2. Flask 账号详情展示

    2023-12-28 23:18:06       52 阅读
  3. Jenkins的shared library相关

    2023-12-28 23:18:06       57 阅读
  4. C语言之结构体

    2023-12-28 23:18:06       43 阅读
  5. c++ day2

    2023-12-28 23:18:06       57 阅读
  6. MySQL中的SIGNAL语句

    2023-12-28 23:18:06       51 阅读
  7. 保龄球。。。。

    2023-12-28 23:18:06       67 阅读
  8. css设置图片左上角加文字

    2023-12-28 23:18:06       53 阅读
  9. Leetcod面试经典150题刷题记录 —— 栈篇

    2023-12-28 23:18:06       61 阅读