zoukankan      html  css  js  c++  java
  • 414. Third Maximum Number

    Problem:

    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.
    

    思路

    Solution (C++):

    int thirdMax(vector<int>& nums) {
        if (nums.empty())  return 0;
        int n = nums.size(), count = 0;
        sort(nums.begin(), nums.end(), greater<int>());
        for (int i = 0; i < n; ++i) {
            while (i < n-1 && nums[i] == nums[i+1])  ++i;
            ++count;
            if (count == 3)  return nums[i];  
        }
        if (count < 3)  return nums[0];
        return 0;
    }
    

    性能

    Runtime: 20 ms  Memory Usage: 9.6 MB

    思路

    Solution (C++):

    
    

    性能

    Runtime: ms  Memory Usage: MB

    相关链接如下:

    知乎:littledy

    欢迎关注个人微信公众号:小邓杂谈,扫描下方二维码即可

    作者:littledy
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。
  • 相关阅读:
    HIFU控制器的显示板
    风扇控制板
    直流源控制板
    HIFU的心脏
    强劲的全桥驱动
    脑电模块
    另一个12导联心电模块
    数据处理,pandas方面遇到的问题
    6.13 django
    python 零基础学习之路-06 常用模块
  • 原文地址:https://www.cnblogs.com/dysjtu1995/p/12684195.html
Copyright © 2011-2022 走看看