LeetCode Hot100 哈希相关题目(1、49、128)C++

LeetCode 1

#include <iostream>
#include <vector>

using namespace std;
class Solution {
   
   
public:
    vector<int> twoSum(vector<int>& nums, int target) {
   
   
        vector<int> res;
        unordered_map<int,int> hash_map;
        for(int i=0;i<nums.size();i++){
   
   
            int another=target-nums[i];
            if(hash_map.count(another))
            {
   
   
                res={
   
   hash_map[another],i};
                return res;
            }
            hash_map[nums[i]]=i;

        }
        return {
   
   };
    }
};

LeetCode 49

#include <iostream>
#include <vector>
#include <unordered_map>
#include <algorithm>
### 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; } } } } ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值