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
<think>好的,我现在需要解决用户遇到的CMake错误:“Cannot findsource file: parser.cxx”。用户提供的错误信息指向第三方库libstudxml的CMakeLists.txt文件,具体是在add_library命令时找不到源文件parser.cxx。我需要根据用户的引用内容和之前的经验来分析可能的原因和解决方法。首先,我应该回忆一下CMake的基本工作原理。根据引用[2],CMake通过CMakeLists.txt文件生成makefile,用户执行cmake命令时需要指向该文件所在的目录。如果add_library找不到源文件,可能是因为路径设置不正确,或者文件确实不存在。 接下来,用户提到的错误发生在third-party/libstudxml.build/CMakeLists.txt的第52行。这里可能的情况是,add_library命令中列出的源文件parser.cxx的路径不正确。根据引用[3],在CMakeLists.txt中,添加源文件通常需要指定正确的路径,尤其是在项目结构复杂或有多个子目录的情况下。例如,如果parser.cxx位于某个子目录中,但CMakeLists.txt中没有正确设置相对路径,就会导致找不到文件。另外,引用[4]展示了一个项目结构示例,其中CMakeLists.txt需要正确组织源文件和头文件的路径。如果libstudxml的源代码结构发生了变化,或者parser.cxx被移动到了其他目录,而CMakeLists.txt没有相应更新,也会引发这个问题。可能的解决方法包括:1.检查parser.cxx是否实际存在于指定的路径中。用户需要确认third-party/libstudxml.build目录下是否存在parser.cxx,或者是否在正确的子目录里。2.确保CMakeLists.txt中add_library命令的源文件路径正确。可能需要使用相对路径,比如${CMAKE_CURRENT_SOURCE_DIR}/parser.cxx,或者绝对路径。3.如果libstudxml是作为子模块或外部项目引入的,可能需要先构建或配置该子项目,确保源文件生成。例如,某些项目会在配置阶段生成源文件,如果生成步骤失败,文件就会缺失。4.检查是否有拼写错误或文件名大小写不一致的情况,特别是在区分大小写的文件系统中。 5.查看libstudxml的文档或构建说明,确认是否有特殊的构建步骤或依赖需要处理。 此外,根据引用[5],执行cmake ..时,确保在正确的构建目录中,并且项目配置正确。有时候清理构建目录并重新生成可能解决问题。如果用户是自己编写或修改了libstudxml的CMakeLists.txt,可能需要检查add_library中的文件列表是否正确引用了parser.cxx。如果是第三方库的问题,可能需要更新库的版本或提交issue给维护者。总结来说,解决这个问题的步骤应该是:确认文件存在,检查路径设置,确保依赖正确配置,必要时重新生成构建系统。</think>要解决CMake报错`Cannot find source file: parser.cxx`的问题,需从路径配置、文件存在性和构建流程三方面排查。以下是具体步骤: --- ### **1. 确认源文件存在性** 首先检查`parser.cxx`是否实际存在于项目中: ```bash # 进入第三方库目录 cd third-party/libstudxml.build/ # 查找文件是否存在 find . -name "parser.cxx" ``` - 如果文件不存在,可能是代码未完整克隆(如未初始化子模块)或文件被误删。需通过`git submodule update --init`同步子模块[^4]。 - 若文件存在但路径与CMakeLists.txt中声明的不一致,需修正路径。 --- ### **2. 检查CMakeLists.txt中的路径设置** 在`add_library`命令中,需正确指定`parser.cxx`的**相对路径**。例如: ```cmake # 使用CMAKE_CURRENT_SOURCE_DIR确保路径相对于当前CMakeLists.txt add_library( libstudxml SHARED ${CMAKE_CURRENT_SOURCE_DIR}/parser.cxx # 显式声明路径 other_source_files.cpp ) ``` - 若文件在子目录中,需添加完整路径:`src/parser.cxx`[^3]。 - 避免硬编码绝对路径,否则移植性差。 --- ### **3. 确保构建流程正确** 若`parser.cxx`是**自动生成的文件**(如由工具生成): 1. 需在`add_library`前添加生成命令: ```cmake # 生成parser.cxx的步骤(示例) execute_process( COMMAND python generate_parser.py # 假设通过脚本生成 WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} ) ``` 2. 使用`add_custom_command`确保生成顺序: ```cmake add_custom_command( OUTPUT parser.cxx COMMAND python generate_parser.py DEPENDS generate_parser.py ) add_library(libstudxml SHARED parser.cxx) ``` --- ### **4. 清理并重新构建** 删除旧的构建缓存,重新生成: ```bash rm -rf build/ # 清理旧构建 mkdir build && cd build cmake .. # 重新配置 make ``` --- ### **5. 其他常见原因** - **拼写错误**:检查文件名是否与代码中完全一致(如大小写)。 - **文件编码问题**:罕见情况下,文件编码异常会导致CMake无法识别。 - **权限问题**:确保`parser.cxx`有可读权限。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值