1.兩數之和
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int,int>m;
for(int i=0,j=0;i<nums.size();i++){
int r=target-nums[i];
if(m.count(r)) return {m[r],i}; //一定要用m.count
m[nums[i]]= i;
}
return {};
}
};
49.字母異位詞分組
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
unordered_map<string,vector<string>> hash;//雜湊表
for(auto &str:strs){
string nstr =str;//複製一份
sort(nstr.begin(),nstr.end());
hash[nstr].push_back(str);//雜湊找
}
vector<vector<string>> res;
for(auto &item: hash) res.push_back(item.second);
return res;
}
};
128.最長連續子序列
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
unordered_set<int>m;
for(auto x:nums){
m.insert(x);//先插入
}
int res=0;
for(auto x:m){
if(!m.count(x-1)){//連續的開頭不存在
int t=x;
int sum=1;
while(m.count(x+1)){
sum++;
x++;
}
res=max(res,sum);
}
}
return res;
}
};
283. 移動零
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int j=0;
for(int i=0;i<=nums.size()-1;i++){
if(nums[i]!=0){//只需要雙指標前面的順序調整好,把後面再置為0就可以
nums[j++]=nums[i];
}
}
for(;j<=nums.size()-1;j++){
nums[j]=0;
}
}
};
11. 盛最多水的容器
class Solution {
public:
int maxArea(vector<int>& height) {
int i = 0, j = height.size() - 1, res = 0;
while(i < j) {//雙指標往中間靠
res = height[i] < height[j] ?
max(res, (j - i) * height[i++]):
max(res, (j - i) * height[j--]);
}
return res;
}
};
15. 三數之和
42.接雨水