两数之和
思路一
暴力解法,两层for循环,时间复杂度O(n2),空间复杂度O(1)
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> result;
for(int i=0;i<nums.size();i++){
for(int j=i+1;j<nums.size();j++){
if(nums[i]+nums[j]==target){
result.push_back(i);
result.push_back(j);
return result;
}
}
}
return {};
}
};
思路二
此处引路哈希表介绍:哈希表,本题在查询
target-nums[i]
的时候花费了O(n)的时间复杂度,因此希望通过哈希表降低查询的时间复杂度,可以使用unordered_set
或unordered_map
,他的查询时间复杂度为O(1)
但是由于本题需要返回下标,所以使用unordered_set
不可以(find函数返回迭代器,不是下标)
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> result;
//此处也可以使用map<int,int>或multimap<int,int>但是时间复杂度变高(O(logn))
//使用multimap<int,int>插入语句需要用multimap.insert({nums[i],i});
unordered_map<int,int> hashmap;
for (int i = 0; i < nums.size(); i++) {
auto j = hashmap.find(target - nums[i]);
if (j != hashmap.end()) {
result.push_back(j->second);
result.push_back(i);
return result;
}
else {
//nums[i]是键,i是值
hashmap[nums[i]]=i;
}
}
return {};
}
};
字母异位词分组
本题可以将每个string排序,然后找到排序后相同的返回,可以使用
unordered_map
,其中的键是排序后的string,值是与当前键相同的排序前的string的集合,然后使用迭代器遍历unordered_map
,得到结果放入result中
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
vector<vector<string>> result;
unordered_map<string, vector<string>> mmap;
for (int i = 0; i < strs.size(); i++) {
//给出排序后的字符串作为键
string str = strs[i];
sort(str.begin(), str.end());
//排序前的字符串作为值
mmap[str].push_back(strs[i]);
}
//此处需要特别注意
//循环map的时候需要用到迭代器i,直接指向键
for (auto i=mmap.begin() ; i != mmap.end(); i++) {
result.push_back(i->second);
}
return result;
}
};
最长连续子序列
无需有序,只需要找当前数加一在不在数组中即可,即遍历
x
,寻找x+1
,x+2
…在不在数组中,找到连续的最大值即可
因此可以选用unordered_set
,因为不需要重复的,也不需要有顺序,证明有x+1
,x+2
…即可,同时时间复杂度为O(1)
此处注意一个多遍历的情况,就是
x+1
在遍历的时候,因为x
已经遍历过了,所以x+1
不会比x
多,为了消除这种情况,只需要判断x-1
在不在数组中,如果在说明已经遍历过,如果不在就继续
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
int count = 1,max=0;
unordered_set<int> st;
for (int i = 0; i < nums.size(); i++) {
st.insert(nums[i]);
}
//得到去重的st
for (auto p = st.begin(); p != st.end(); p++) {
//排除重复遍历
if (st.find(*p - 1) != st.end())continue;
//找到了x+1
auto fin = st.find(*p + 1);
//循环找下一个x+1
while (fin!= st.end()) {
fin = st.find(*fin + 1);
count++;
}
if (count > max){
max = count;
}
//重新赋值
count=1;
}
return max;
}
};