Acy夕拾算法 Week1_day3
LeetCode 1. 两数之和
/*
我的思路:
·哈希表,存遍历过的数,target-新来的数b = 能与b凑成目标值的数a
·将 a 与哈希表中的数做判断,里面是否有 a
·答案要返回位置,
··用vector存的话,查找又要遍历一遍,pass
··用map<数值,下标>,------通过了?数值key有重复不应该被覆盖掉吗?XXXX不会覆盖,会忽略新插入
~··!!!map插入已存在key时,不会覆盖,而是忽略插入操作!!!
··所以即便要查找 数值key,也不需要用multimap可重复的key,而且multimap怎么按key查值?一个key对应多个value(下标),还要再去判断
~··!!!unordered_map是基于哈希表实现的,插入查找复杂度为O(1)
~··!!!map是基于红黑树实现的,插入查找复杂度为O(log n)
··用unordered_map
*/
| 映射 | 排序 | 重复 | 实现(插入查找的时间复杂度) |
|---|---|---|---|
| map | 自动排序 | 无 | 红黑树O(log n) |
| multimap | 自动排序 | 可 | 红黑树O(log n) |
| unordered_map | 无序 | 无 | 哈希表O(1) |
遍历方法1 用.count查
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int,int> hasmap;//《数值,下标》
vector<int> res(2, -1);
for(int i = 0; i < nums.size(); i++)
{
res[1] = i;
if(hasmap.count(target-nums[i]) > 0)
{
res[0] = hasmap[target-nums[i]];
return res;
}
else
{
hasmap.insert({nums[i], i});
}
}
return res;
}
};
遍历方法2 用find查
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int,int> hasmap;//《数值,下标》
// vector<int> res(2, -1);
for(int i = 0; i < nums.size(); i++)
{//代码随想录
if(hasmap.find(target-nums[i]) == hasmap.end())
hasmap.insert({nums[i], i});//没找到就插入
else
return {hasmap[target-nums[i]], i};//找到直接返回
}
return {};
}
};
LeetCode 3. 无重复字符的最长子串
/*
整理思路:
·重复字符–滑动窗口(set+双指针);只需要返回最大长度;
·set<字符>存储窗口中的字符;左指针-窗口的开始;右指针-窗口的结束;
·判断set里是否有这个字符cc
·有cc,让right把窗口移动到没有cc的位置,移动过程中:弹出所指向的字符、长度++
·没有cc,插入cc,长度++,扩充窗口;
https://www.bilibili.com/video/BV113411v7Ak/?spm_id_from=333.337.search-card.all.click&vd_source=2d8dcc7dd5263daca547e215ddfd99e2
·指针都向右移动,右指针不断往右划不断放入,遇到重复,左指针右划(同时删掉当前元素)!直到!右指针满足条件;
·右指针滑动时不断更新:当前长度±、最大长度、set
*/
class Solution {
public:
int lengthOfLongestSubstring(string s) {
unordered_set<char> ccset;
int left = 0, right = 0;
int length = 0, max_length = 0;
for( ; right < s.size(); right++)//right<长度即可
{
if(ccset.count(s[right]) > 0)
{
while(ccset.count(s[right]) != 0)
{
ccset.erase(s[left]);
left++;
length--;
}
//不要忘记加入right的值ccset
ccset.insert(s[right]);
length++;
}
else
{
ccset.insert(s[right]);
length++;
if(length > max_length)
max_length = length;// max_length++;
}
}
return max_length;
}
};

被折叠的 条评论
为什么被折叠?



