242. 有效的字母异位词
复习知识点:本题常见的两个思路,一个比较简单,直接进行排序,然后判断排序后的两个新单词是不是一一对应的字母,第二种思路使用数组进行存储每个字母的出现次数,在遍历第二个单词的时候进行次数的减少,当发现次数减少到负数的时候说明两个单词的字母出现次数不同,返回false.
// class Solution {
// public:
// bool isAnagram(string s, string t) {
// if(s.size() != t.size())
// return false;
// sort(s.begin(), s.end());
// sort(t.begin(), t.end());
// for(int i = 0;i < s.size();++i)
// if(s[i] != t[i])
// return false;
// return true;
// }
// };
class Solution {
public:
bool isAnagram(string s, string t) {
if(s.size() != t.size())
return false;
// 26个字母,初始出现次数都为0
vector<int> hash(26, 0);
// 首先统计第一个单词的字母出现次数
for(char ch : s)
// 将字母转换为数组下标
++hash[ch - 'a'];
// 遍历第二个单词,每次对出现的字母进行相减,如果次数变为负数了,那就说明出现次数不一致返回false
for(char ch : t)
{
--hash[ch - 'a'];
if(hash[ch - 'a'] < 0)
return false;
}
return true;
}
};
268. 丢失的数字
复习知识点:本题思路较为简单,排序后依次查找不存在的数字,记录之后返回即可
class Solution {
public:
int missingNumber(vector<int>& nums) {
int res;
sort(nums.begin(), nums.end());
for(int i = 0;i < nums.size();++i)
{
if(nums[i] != i)
{
res = i;
break;
}
if(i == nums.size() - 1)
res = nums.size();
}
return res;
}
};
283. 移动零
复习知识点:本题使用比较简单的覆盖方式进行非零元素的填坑,然后将末尾缺少的位置补零.
class Solution {
public:
void moveZeroes(vector<int>& nums) {
// 直接覆盖掉0,在数组末尾补0即可,即将不是零的元素依次放在当前索引位置
int index = 0;
for(int num : nums)
{
// index迭代在if里面,这样可以跳过元素为0的索引,以使得非零元素全部放在前面
if(num != 0)
{
nums[index] = num;
++index;
}
}
for(int i = index;i < nums.size();++i)
{
nums[i] = 0;
}
}
};