414. Third Maximum Number(python+cpp)

本文详细解析了如何在给定的整数数组中找到第三大的数,如果不存在则返回最大数。通过Python和C++代码实现,讨论了不同情况下的处理策略,包括数组长度小于3的情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

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.

解释:
返回数组中的最大的第三个数,需要注意的是,如果数组的长度小于3,直接返回最大的数就好,如果数组的长度刚好等于3,直接返回最小的数就好。注意,重复的数字当成一个数字看。所以需要先set()一下。
python代码:

class Solution(object):
    def thirdMax(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        nums=set(nums)
        len_nums=len(nums)
        if len_nums<3:
            return max(nums)
        if len_nums==3:
            return min(nums)
        nums.remove(max(nums))
        nums.remove(max(nums))
        return max(nums)

上面代码的速度略慢,因为每次都要max()remove(),下面是一个略快的代码:
python代码:

class Solution(object):
    def thirdMax(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        set_nums=set(nums)
        len_set_nums=len(set_nums)
        max_num=max(nums)
        min_num=min(nums)
        if len_set_nums<3:
            return max_num
        if len_set_nums==3:
            return min_num
        else:
            first_max=max_num
            second_max=float('-inf')
            third_max=float('-inf')
            for num in set_nums:
                if num>second_max and num<first_max:
                    second_max,third_max=num,second_max
                elif num>third_max and num<second_max:
                    third_max=num
            return third_max     

c++代码:

class Solution {
public:
    int thirdMax(vector<int>& nums) {
        set<int>_set(nums.begin(),nums.end());
        int len_set=_set.size();
        auto minmax=minmax_element(_set.begin(),_set.end());
        int min_num=*minmax.first;
        int max_num=*minmax.second;
        if(len_set<3)
            return max_num;
        else if(len_set==3)
            return min_num;
        else
        {
            int second_max=INT_MIN;
            int third_max=INT_MIN;
            for(auto num:_set)
            {
                if (num>second_max &&num<max_num)
                {
                    third_max=second_max;
                    second_max=num; 
                }
                else if(num>third_max &&num<second_max)
                    third_max=num;
            }
            return third_max;
        }
    }
};

总结:
突然发现,stl的set是排好序的,所以在c++中可以用set()做,维护一个长度为3的set(),每次都insert(),当size()>3以后则erase()第一个,如果最后set的长度等于3,则返回第一个元素(最小的那个),如果小于3,则返回最后的那个(rbegin(),证明原数组中不同的数字的个数不到3个,最大的那个 )。主要还是利用了stl set顺序的特性。
代码如下:

#include <set>
using namespace std;
class Solution {
public:
    int thirdMax(vector<int>& nums) {
        set<int>_set;
        for(auto num:nums)
        {
            _set.insert(num);
            while(_set.size()>3)
                _set.erase(_set.begin());
        }
        return (_set.size()==3)?*_set.begin():*_set.rbegin();
    }
};
Requirements The code is tested on clean Ubuntu 20.04 with ROS noetic installation. Install the required package toppra: sudo pip3 install toppra catkin_pkg PyYAML empy matplotlib pyrfc3339 Run the code 1. Download and compile the code git clone https://github.com/ZJU-FAST-Lab/Primitive-Planner.git cd Primitive-Planner catkin_make -DCMAKE_BUILD_TYPE=Release 2. Generate the motion primitive library cd src/scripts python3 swarm_path.py The generated motion primitive library is stored in "src/planner/plan_manage/primitive_library/". 3. Run the planner In the "Primitive-Planner/" directory: source devel/setup.bash # or setup.zsh cd src/scripts python3 gen_position_swap.py 20 # It will generate the swarm.launch with 20 drones roslaunch primitive_planner swarm.launch Wait until all the nodes have their launch process finished and keep printing "[FSM]: state: WAIT_TARGET. Waiting for trigger". Open another terminal, publish the trigger cd src/scripts bash pub_trigger.sh Then the drones (drone number is 40) will start to fly like this Change the drone number when executing "python3 gen_position_swap.py <drone_number>". Before starting the "roslaunch" command, please open another terminal and run "htop" to monitor the Memory usage and CPU usage. Each drone requires about 200 MB memory. Keep the htop opened for entire flight. The computation time is printed on the terminal in blue text, named as "plan_time". To get the accurate computation time, please fix the CPU frequency to its maximum by sudo apt install cpufrequtils sudo cpufreq-set -g performance Otherwise the CPU will run in powersave mode with low frequency. (根据上述代码帮我生成复现最适合在乌班图20.04复现的详细的实现过程和每一步的预期输出,需要安装的每个东西的乌班图20.04兼容版本,还有每一步是否需要创建虚拟环境,每一步是在创建的虚拟环境进行还是不进入虚拟环境的终端进行)
07-09
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值