C++ 查找众数代码分析:错误判断条件修正

这段代码旨在查找数组中出现次数超过一半的元素(众数),但存在一个逻辑错误。

原始代码:

#include <unordered_map>
#include <iostream>
using namespace std;
class Solution {
public: 
    int majorityElement(vector<int>& nums) {
        unordered_map<int, int> hashmap;
        int n = nums.size();
        int num = n / 2;
        int orll = 0;
        for (int i = 0; i < n; i++) {
            hashmap[nums[i]]++;
        }
        for (const auto& pair : hashmap) {
            if (pair.second > n) {
                orll = pair.first;
            }
        }
        return orll;
    }
};

int main() {
    int nums[] = {3, 2, 3};
    int solution = Solution().majorityElement(nums);
}

问题分析:

原始代码中,第二个 for 循环用于遍历 hashmap,并判断每个元素的出现次数是否超过数组长度的一半。错误在于判断条件使用了 > 运算符,即 pair.second > n

正确判断条件:

根据题意,需要查找出现次数 超过或等于 一半的元素,因此判断条件应使用 >= 运算符,即 pair.second >= num

修正后的代码:

#include <unordered_map>
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public: 
    int majorityElement(vector<int>& nums) {
        unordered_map<int, int> hashmap;
        int n = nums.size();
        int num = n / 2;
        int orll = 0;
        for (int i = 0; i < n; i++) {
            hashmap[nums[i]]++;
        }
        for (const auto& pair : hashmap) {
            if (pair.second >= num) {
                orll = pair.first;
            }
        }
        return orll;
    }
};

int main() {
    vector<int> nums = {3, 2, 3};
    int solution = Solution().majorityElement(nums);
    cout << "Majority element: " << solution << endl;
    return 0;
}

代码改进:

  • 修正了判断条件,使用 >= 运算符代替 > 运算符。
  • nums 数组的类型更改为 vector<int>,便于使用。
  • main 函数中添加了输出结果的语句,方便查看结果。

希望以上分析能够帮助你理解代码中的逻辑错误并修正代码。

C++ 查找众数代码分析:错误判断条件修正

原文地址: http://www.cveoy.top/t/topic/bL0V 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录