第一题:
题目:
题意:就是移除字母异位词,使得这个字符串数组中不存在字母异位词。那么什么是字母异位词呢,简单来理解就是把两个字符串进行排序之后长的一样,就是字母异位词,比如两个字符串aabb和bbaa,把bbaa按照字典序排序之后变成aabb,就变成了前一个字符串,这就是字母异位词。
解题思路:因为数据范围很小,简单模拟一下即可。
代码如下:
class Solution {
public:
vector<string> removeAnagrams(vector<string>& words) {
vector<string> ans;
ans.push_back(words[0]);
for (int i = 1; i < words.size(); i++) {
vector<int> a(26), b(26);
for (auto c : words[i - 1]) a[c - 'a']++;
for (auto c : words[i]) b[c - 'a']++;
for (auto j = 0; j < 26; j++)
if (a[j] != b[j]) {
ans.push_back(words[i]);
break;
}
}
return ans;
}
};
第二题:
题目:
题意:把数组中的数值放到bottom和top之间,把[bottom,top]这个闭区间分割成若干个闭区间,然后求哪个闭区间最长就行了
解题思路:
①将给定的数组special从小到大进行排序
②遍历该数组,mx = max(special[i]-special[i-1],mx)
③这个结果是special数组最小值和最大值分割的区间中最长的闭区间,然后再跟[bottom,special[0]]、[special[k-1],top]这两个闭区间比较,取出最大值就是答案咯
代码如下:
class Solution {
public:
int maxConsecutive(int bottom, int top, vector<int>& special) {
sort(special.begin(),special.end());
int mx = 0;
int k = special.size();
for(int i = 1 ; i < k ; ++i){
mx = max(special[i] - special[i-1] - 1,mx);
}
mx = max(mx , special[0] - bottom);
mx = max(mx , top - special[k-1]);
return mx;
}
};
第三题:
题目:
题意:
给定一个数组,然后用该数组中的元素进行按位与,当然每个元素只能用一次噢,也可以不用,然后让你求,用哪些元素可以使得按位与的结果大于0,求用的最多的元素的方案,当然可能方案不止一个,所以求用的最多元素是多少就可以了
解题思路:
参考题中的例子,一个数组candidates = [16,17,71,62,12,24,14],转成二进制观察结果如下:
16->0010000
17->0010001
71->1000111
62->0111110
12->0001100
24->0011000
14->0001110
因为按位与的定义是相同为1,不同为0,所以要使得最后结果大于0,选中的元素中某一列必须全为1。这样子看就很直观咯,找每一列中出现1次数最多的数值是多少,就是答案了。然后求一个数哪些位上是1,我用lowbit每次取出该数2的最小的幂,然后求一下是几次幂,进行记录,最后再遍历一遍标记数组,求出mx值即可
那么lowbit大家都应该知道是什么吧,就是x & -x
求是几次幂的函数就随便写一个
int log2(int a) {
int sum = 0;
while(1){
if(a >>= 1)
++sum;
else
break;
}
return sum;
}
整体代码如下:
class Solution {
public:
int log2(int a) {
int sum = 0;
while(1){
if(a >>= 1)
++sum;
else
break;
}
return sum;
}
int lowbit(int x){
return x & -x;
}
int largestCombination(vector<int>& candidates) {
int cnt[32] , mx = 0;
memset(cnt , 0 , sizeof cnt);
int len = candidates.size();
for(int i = 0 ; i < len ; ++i){
while(candidates[i]){
int temp = lowbit(candidates[i]);
int ans = log2(temp)+1;
++cnt[ans];
candidates[i] -= lowbit(candidates[i]);
}
}
for(int i = 1 ; i <= 31 ; ++i){
mx = max(mx , cnt[i]);
}
return mx;
}
};
第四题就不放了,因为不会。这里就放个力扣上的题解链接
第四题题解点击此处