Majority Element I, II

Majority Element


Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.

You may assume that the array is non-empty and the majority element always exist in the array.

int majorityElement(vector<int>& nums) {
        int maxData=-1;
        int count=0;
        for(int i=0; i<nums.size(); i++){
            if(maxData==nums[i])
                count++;
            else if(count==0){
                maxData=nums[i];
                count=1;
            }
            else{
                count--;
            }
        }
        return maxData;
    }




2. Majority Element II

Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. The algorithm should run in linear time and in O(1) space.

解法来自:http://www.2cto.com/kf/201507/412935.html

    vector<int> majorityElement(vector<int>& nums) {
        vector<int> res;
        int m=-1, n=-1, cm=0, cn=0;//该题解法实际上是在上一题的基础上略作修改得到的解法
        for(int i=0; i<nums.size(); i++){
            if(m==nums[i]){
                cm++;
            }
            else if(n==nums[i]){
                cn++;
            }
            else if(cm==0){
                cm=1;
                m=nums[i];
            }
            else if(cn==0){
                cn=1;
                n=nums[i];
            }
            else{
                cm--;
                cn--;
            }
        }
        cm=0, cn=0;
        for(auto &it : nums){//注意上题是假设测试用例都包含一个Majority Element,本题没有这样的假设
            if(it==m)
                cm++;
            else if(it==n)
                cn++;
        }
        if(cm>(nums.size()/3))
            res.push_back(m);
        if(cn>(nums.size()/3))
            res.push_back(n);
        return res;
    }




### 如何使用 Keil5 Hex 文件 对于仅拥有已编译好的 hex 文件而无源文件的情况,在 Keil V5 平台上直接hex 文件至单片机(如华大单片机)需采取特定的方法,因为直接调用该平台进行此类操作不可行[^1]。 #### 设置 Output 路径 进入 Keil 的 output 设置界面,指定要录的 hex 文件的具体位置。确保在路径输入框中填完整的 hex 文件名称并附带 `.hex` 扩展名;缺少此扩展名可能导致系统继续尝试录先前编译的结果而非所选的 hex 文件[^3]。 #### 配置 Flash 工具选项 针对不同类型的微控制器(MCU),可能还需调整 flash 下载工具的相关配置参数以匹配目标设备的要求。这一步骤通常涉及选择合适的编程算法以及设定通信接口等细节[^2]。 #### 启动下载过程 完成上述准备工作之后,可以通过点击调试窗口内的 “Download” 或者快捷菜单里的相应命令来启动实际的程序入流程。如果一切顺利的话,软件会自动连接硬件并将选定的 hex 数据传输到 MCU 中存储起来[^4]。 ```python # Python 示例代码用于说明自动化脚本概念 (并非真实实现) def download_hex_to_mcu(hex_file_path, mcu_type): """ 自定义函数模拟将 HEX 文件下载到指定型号的 MCU 上 参数: hex_file_path -- 完整路径字符串指向待上传的 .hex 文件 mcu_type -- 字符串表示的目标单片机类型标识符 返回值: 成功则返回 True ,失败抛出异常信息 """ try: configure_output_settings(hex_file_path) # 设定输出设置 select_flash_tool(mcu_type) # 挑选适合的闪存工具 execute_download_command() # 发送下载指令 return True # 表明成功结束 except Exception as e: raise RuntimeError(f"Failed to upload {hex_file_path}: {e}") ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值