第一题:移除字母异位后的结果数组
思路:模拟。用哈希表来存储一个排序好的字符串和下标
代码:
class Solution {
public:
vector<string> removeAnagrams(vector<string>& words) {
unordered_map<string, int> mp;
vector<string> ans;
for(int i = 0; i < words.size(); i ++){
string s = words[i];
sort(s.begin(), s.end());
if(!mp.size()|| mp.find(s) == mp.end()){
mp[s] = i;
ans.push_back(words[i]);
}
if(mp.find(s) != mp.end()){
if(i - mp[s] > 1) ans.push_back(words[i]);
mp[s] = i;
}
}
return ans;
}
};
第二题:不含特殊层的最大连续楼层数
思路:排序+双指针模拟。先将数组进行排序,排序后模拟
代码:
class Solution {
public:
int maxConsecutive(int bottom, int top, vector<int>& s) {
sort(s.begin(), s.end());
int n = s.size();
int ans = 0;
for(int i = 0; i < n; i ++){
if(bottom > top) break;
int m = s[i] - bottom;
ans = max(m, ans);
bottom = s[i] + 1;
}
ans = max(ans, top - bottom + 1);
return ans;
}
};
第三题:按位与结果大于零的最长组合
思路:我一直以为是序列DP,但是写了半天都不对就发放弃了,最后看题解发现是用一个数组来存放二进制为数,找到1的最多的那个。
代码:
class Solution {
public:
int largestCombination(vector<int>& candidates) {
int a[32];
memset(a, 0, sizeof a);
for(auto &t : candidates){
for(int j = 0; j < 32; j ++){
if(t >> j & 1){
a[j] ++;
}
}
}
int res = 0;
for(int i = 0; i < 32; i ++) res = max(res, a[i]);
return res;
}
};
第四题有一些位不是太清楚后面再看看吧