leetcode hot100 之 多数元素

该博客讨论了一种在给定数组中找出出现次数超过数组长度一半的数字的方法。提供了两种思路:哈希法和排序法。哈希法通过遍历数组并使用哈希表记录每个数字出现的次数,当某数字计数超过n/2时返回该数字。时间复杂度为O(n),空间复杂度为O(n)。而排序法虽然能找出主要元素,但时间复杂度较高,为O(nlogn)。代码示例中展示了哈希法的实现。

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

题目

给定一个数组。其中某个数字出现次数大于 ⌊ n/2 ⌋ 次,请找出这个数字。

输入:nums = [2,2,1,1,1,2,2]
输出:2

原题链接:https://leetcode.cn/problems/majority-element/

思路

思路1

哈希法,维护一个哈希表,记录数字的次数,超过 n/2即可。

  • 复杂度分析
    • 时间复杂度 O(n)。遍历一次数组即可。实际不用遍历完就能找到结果。
    • 空间复杂度 O(n)。实际储存数字最多为 n/2 个。
思路2

排序法。排序完后,下标为 n/2 的数字即是答案。

  • 复杂度分析
    • 时间复杂度 O(nlogn)。排序最快 O(nlogn)。
    • 空间复杂度 O(1)。如果能在原数组中排序最好。

代码

这里只写哈希法作为示例。

class Solution {
public:
    int majorityElement(vector<int>& nums) {
        unordered_map<int, int> table;
        int n = nums.size();
        for (auto num: nums) {
            if (table.count(num) == 0) {
                table[num] = 0;
            }
            table[num]++;
            if (table[num] > n/2) {
                return num;
            }
        }
        return -1;
    }
};
### LeetCode Hot 100 Problems C++ Solutions 以下是针对LeetCode热门题目的一些常见问题及其C++解决方案的概述。这些解答基于常见的算法思想,如滑动窗口、哈希表以及字符串操作等。 #### 反转字符串 对于反转字符串的问题,可以采用双指针的方法来交换数组中的字符位置[^1]。这种方法的时间复杂度为O(n),其中n是字符串长度,而空间复杂度为O(1)。 ```cpp class Solution { public: void reverseString(std::vector<char>& s) { int n = s.size(); int left = 0, right = n - 1; while (left < right) { std::swap(s[left++], s[right--]); } } }; ``` #### 不重复最长子串 不重复最长子串可以通过滑动窗口的思想实现[^2]。通过维护一个动态变化的窗口并记录当前无重复字符的最大长度,可以在一次遍历中完成计算。 ```cpp class Solution { public: int lengthOfLongestSubstring(const std::string& s) { std::unordered_set<char> window; int maxLength = 0, start = 0; for(int i = 0;i<s.length();i++) { char currentChar = s[i]; while(window.find(currentChar)!=window.end()) { window.erase(s[start]); ++start; } window.insert(currentChar); maxLength = std::max(maxLength,i-start+1); } return maxLength; } }; ``` #### 多数元素查找 多数元素查找问题是另一个经典案例,通常可以用摩尔投票法或者哈希映射方法解决[^3]。这里展示的是利用哈希表的方式,其时间复杂度为O(n),空间复杂度同样为O(n)。 ```cpp class Solution { public: int majorityElement(std::vector<int>& nums) { std::map<int,int> countMap; int threshold = nums.size() / 2; for(auto num : nums){ if(countMap.find(num)==countMap.end()){ countMap[num]=1; }else{ countMap[num]++; } if(countMap[num]>threshold){ return num; } } return -1; } }; ``` #### 广度优先搜索(BFS) 广度优先搜索是一种用于图结构探索的技术,在某些场景下也可以应用于语义关联网络等问题[^4]。下面是一个简单的BFS模板例子: ```cpp #include <queue> #include <vector> void bfs(int root,std::vector<std::vector<int>> adjList){ std::queue<int> q; std::vector<bool> visited(adjList.size(),false); q.push(root); visited[root]=true; while(!q.empty()){ int node=q.front();q.pop(); // Process the node here... for(auto neighbor:adjList[node]){ if(!visited[neighbor]){ q.push(neighbor); visited[neighbor]=true; } } } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值