目录
1.383. 赎金信 - 力扣(LeetCode)
这个题跟242. 有效的字母异位词 - 力扣(LeetCode)这道题目很像,但是有不一样,有效字母只是单纯的计算字符串s中的字母出现的次数是不是跟字符串t中的字母出现的次数相同。
而赎金信需要判断的字符串ransomNote能不能由magzine里的字符构成,也就是说,在ransomNote中出现的字符,一定要在magzine中出现。但是在magzine中出现的字符,不一定要ransomNote出现。于是就有两个要注意的点,第一个是要先遍历magzine,而不是ransomNote,第二个就是不能单纯的直接判断字母是否出现过,而是要判断ransomNote里的字母是否在magzine里面出现过
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
int flag[26] = {0};
// 第一个点
for(int i = 0; i < magazine.length(); i++){
flag[magazine[i] - 'a']++;
}
for(int i = 0; i < ransomNote.length(); i++){
// !!!!第二个点
flag[ransomNote[i] - 'a']--;
// flag[magazine[i] - 'a']--; 不能这样子啊
//立即判断 节约时间
if(flag[ransomNote[i] - 'a'] < 0){
return false;
}
}
// for(int i = 0; i < 26; i++){
// if(flag[i] < 0){
// return false;
// }
// }
return true;
}
};
2.15. 三数之和 - 力扣(LeetCode)
用快慢指针比哈希好
i、left、right分别代表第一个第二个第三个元素
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> result;
sort(nums.begin(), nums.end());
while(int i = 0; i < nums.size(); i++){
if(nums[i] > 0)
{ return reslult;}
// 对a去重
if(i > 0 && nums[i] == nums[i-1]){
continue;
}
int l = i + 1;
int r = nums.size() - 1;
while(l < r ){
if(nums[i] + nums[l] + nums[r] < 0) l++;
else if(nums[i] + nums[l] + nums[r] > 0) r--;
else{
result.push_back(vector<int> {nums[i], nums[l], nums[r]});
// 对b、c去重
while(l < r && nums[l] == num[l+1]) l++;
while(l < r && nums[r] == nums[r-1]) r--;
l++, r--;
}
}
return result;
}
};
if(i > 0 && nums[i] == nums[i-1]){
continue;}
这段代码是对a去重 注意不能写成 nums[i] == nums[i+1] 因为题目要求的是不重复的三元组。基于相同的元素不要有相同的三元组解。而三元组内部的元素是可以重复的。如果用i+1就会跳过一个重复的元素,导致丢失一个解啊