题目列表:
- 349
- 350
- 242
题目349:Intersection of Two Arrays
描述:Given two arrays, write a function to compute their intersection.
例子:Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2].
Note:
Each element in the result must be unique.
The result can be in any order.
代码:
vector<int> Solution349::intersection(vector<int>& nums1, vector<int>& nums2)
{
set<int>nums1_plus, nums2_plus;
nums1_plus.insert(nums1.begin(), nums1.end());//因为集合是不区分元素位置的
nums2_plus.insert(nums2.begin(), nums2.end());
vector<int> res;
int len1 = nums1_plus.size();
for (int x : nums1_plus)
{
if (nums2_plus.find(x) != nums2_plus.end())res.push_back(x);
}
return res;
}
题目350:Intersection of Two Arrays II
描述:Given two arrays, write a function to compute their intersection.
例子:Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2].
Note:
Each element in the result should appear as many times as it shows in both arrays.
The result can be in any order.
代码:
vector<int> Solution350::intersect(vector<int>& nums1, vector<int>& nums2)
{
unordered_map<int, int>nums1_plus, nums2_plus;
for (int x : nums1)nums1_plus[x]++;
for (int x : nums2)nums2_plus[x]++;
vector<int> res;
for (auto x : nums1_plus)
{
if (nums2_plus.find(x.first) != nums2_plus.end())res.insert(res.end(), min(x.second, nums2_plus[x.first]), x.first);
}
return res;
}
题目242: Valid Anagram
描述:Given two strings s and t , write a function to determine if t is an anagram of s.
例子:
1. Input: s = “anagram”, t = “nagaram” Output: true
2. Input: s = “rat”, t = “car” Output: false
Note:
You may assume the string contains only lowercase alphabets.
代码:
bool Solution242::isAnagram(string s, string t)
{
//way 1
//if (s.size() != t.size())return false;
//unordered_map<char, int> s_plus, t_plus;
//for (char x : s)s_plus[x]++;
//for (char x : t)t_plus[x]++;
//for (auto x : s_plus)
//{
// if (t_plus.find(x.first) != t_plus.end())
// {
// if (x.second != t_plus[x.first]) return false;
// }
// else
// return false;
//}
//return true;
//way 2
if (s.size() != t.size()) return false;
vector<int> flag(26);//将26个小写字母映射到对应数组下标,元素为每个字母出现的次数,初始值为0
for (char x : s) flag[x - 'a']++;//计算s字符串中每个字母出现的次数
for (char x : t)
{
flag[x - 'a']--;
if (flag[x - 'a'] < 0)return false;//如果两个字符串等长,且不是变换顺序的话,t中一定存在某个字母数大于s
}
return true;
}
在题目242中,第二种方法的runtime优于第一种方法,在非变换顺序的字符串中可以在遍历结束之前结束。
更多内容请见我的个人博客:AlisaBen