LC217存在重复元素
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
unordered_set<int> s;
for(auto num:nums){
if(s.count(num)){
return true;
break;
}
else s.insert(num);
}
return false;
}
};
LC219存在重复元素II
class Solution {
public:
bool containsNearbyDuplicate(vector<int>& nums, int k) {
//枚举是O(n^2)
unordered_map<int, int> m;
int n=nums.size();
for(int i=0; i<n; ++i){
int freq=m.count(nums[i]);
if(freq){
if(abs(i-m[nums[i]])<=k){
return true;
}
else{
m[nums[i]]=i;
}
}
else m[nums[i]]=i;
}
return false;
}
};
LC36有效的数独
官方题解
class Solution {
public:
bool isValidSudoku(vector<vector<char>>& board) {
int row[9][9];
int col[9][9];
int t[3][3][9];
memset(row, 0, sizeof(row));
memset(col, 0, sizeof(col));
memset(t, 0, sizeof(t));
for(int i=0; i<9; ++i){
for(int j=0; j<9; ++j){
if(board[i][j]!='.'){
int num = int(board[i][j]-'0')-1;//得是0-8
row[i][num]++;//i行这个数出现过多少次
col[j][num]++;//j列这个数出现过多少次
t[i/3][j/3][num]++;
if(row[i][num]>1 || col[j][num]>1 || t[i/3][j/3][num]>1) return false;
}
}
}
return true;
}
};
LC771宝石与石头
class Solution {
public:
int numJewelsInStones(string jewels, string stones) {
unordered_set<char> s;
int ans=0;
for(auto c:jewels){
s.insert(c);
}
for(auto c:stones){
if(s.count(c)){
ans++;
}
}
return ans;
}
};
LC811子域名访问计数
class Solution {
public:
vector<string> subdomainVisits(vector<string>& cpdomains) {
vector<string> ans;
unordered_map<string, int> m;
for(auto s:cpdomains){
int index=s.find(' ');//空格的位置
int num=stoi(s.substr(0, index));
string dName=s.substr(index+1);
while(index>0){//没指向last
m[dName] += num;
index=dName.find('.');
dName=dName.substr(index+1);
}
}
for(auto s:m){
ans.push_back(to_string(s.second) + " " + s.first);
}
return ans;
}
};
知识
- memset
- 字符串find,stoi,to_string,substr
while(index>0){//没指向last
m[dName] += num;
index=dName.find('.');
dName=dName.substr(index+1);
}
- 哈希,first,second
ans.push_back(to_string(s.second) + " " + s.first);