两数之和
思路:将原数组排序,并记录之前的下标位置,排序双指针即可
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> ans;
vector<pair<int,int>> in;
for(int i=0; i<nums.size(); i++)
{
in.push_back({nums[i], i});
}
sort(in.begin(), in.end());
for(int i=0, j=nums.size()-1; i<j;)
{
if(in[i].first + in[j].first == target)
{
ans.push_back(in[i].second);
ans.push_back(in[j].second);
break;
}
while(in[i].first + in[j].first > target) j--;
while(in[i].first + in[j].first < target) i++;
}
return ans;
}
};
字母异位词分组
思路: 对每一个字符串进行字典序排序,然后根据字典序排序结果存入map,再依次输出即可
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
vector<vector<string>> ans;
map<string, vector<string>> mp;
for(int i=0; i<strs.size(); i++)
{
string str(strs[i]);
sort(str.begin(), str.end());
mp[str].push_back(strs[i]);
}
for(auto &[u , v] : mp)
{
ans.push_back(v);
}
return ans;
}
};
最长连续序列
暴力做法:O(N*N)
遍历数组取x,对于每一个x都先后遍历直到不能再遍历,然后计算ans的最大值
优化做法:O(N*logN),如果愿意把set的查找认为是O(1)的话,那就是O(N)复杂度、
如果我们要从X开始找的话,切好数组中也有X-1存在,那么我们就可以跳过X,而等着之后测试X-1即可。因为以X-1开始一定结果更好,X就不需要测试了
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
int ans = 0;
unordered_set<int> mp;
for(auto x: nums)
{
mp.insert(x);
}
for(auto x : mp)
{
if(mp.find(x-1) != mp.end()) continue;
int cnt = 1, temp = x+1;
while(mp.count(temp))
{
temp++;
cnt++;
}
ans = max(ans, cnt);
}
return ans;
}
};