DAY 11
1.LeetCode 3. 无重复字符的最长子串
考察点:双指针 滑动窗口 哈希表
解法:
(双指针扫描) O(n)
定义两个指针 i,j(i<=j)i,j(i<=j),表示当前扫描到的子串是 [i,j][i,j] (闭区间)。扫描过程中维护一个哈希表unordered_map<char,int> hash,表示 [i,j][i,j]中每个字符出现的次数。
线性扫描时,每次循环的流程如下:
(1)指针 jj 向后移一位, 同时将哈希表中 s[j]s[j] 的计数加一: hash[s[j]]++;
(2)假设 jj 移动前的区间 [i,j][i,j] 中没有重复字符,则 jj 移动后,只有 s[j]s[j] 可能出现2次。因此我们不断向后移动 ii,直至区间 [i,j][i,j]中 s[j]s[j] 的个数等于1为止;
复杂度分析:由于 i,ji,j 均最多增加n次,且哈希表的插入和更新操作的复杂度都是 O(1)O(1),因此,总时间复杂度 O(n).
具体实现代码如下:
class Solution {
public:
int lengthOfLongestSubstring(string s)
{
unordered_map<char,int>heap;
int res = 0;//存储最大长度
for(int i = 0,j = 0;j<s.size();j++)
{
heap[s[j]]++;
while(heap[s[j]]>1) heap[s[i++]]--;
res = max(res,j-i+1);
}
return res;
}
};
2.AcWing 870. 约数个数
考察点:约数个数 哈希表
从零开始到α有多少种取法,就说明约数有多少种
int范围内,约数最多为1500左右
#include<iostream>
#include<algorithm>
#include<unordered_map>
#include<vector>
using namespace std;
typedef long long LL;
const int N = 110,mod = 1e9+7;
int main()
{
int n;
cin>>n;
unordered_map<int,int>primes;
while(n--)
{
int x;
cin>>x;
for(int i=2;i<=x/i;i++)
while(x%i==0)
{
x/=i;
primes[i]++;
}
if(x>1) primes[x]++;//因为一个数x最多有一个大于sqrt(x)的质因子,for循环里求的是2到sqrt(x)的质因子,所以要单独考虑是否有,如果有就和for循环里一样的操作
}
LL res = 1;
for (auto p : primes) res = res * (p.second + 1) % mod;
cout<<res<<endl;
return 0;
}
3.AcWing 871. 约数之和
考察点:约数之和 哈希表
具体实现代码如下:
#include<iostream>
#include<algorithm>
#include<unordered_map>
#include<vector>
using namespace std;
const int N = 110,mod = 1e9+7;
typedef long long LL;
int main()
{
int n;
cin>>n;
unordered_map<int,int>primes;
while(n--)
{
int x;
cin>>x;
for(int i=2;i<=x/i;i++)
while(x%i==0)
{
x/=i;
primes[i]++;
}
if(x>1)primes[x]++;
}
LL res = 1;
for(auto p:primes)
{
LL a = p.first,b = p.second;//a是底数,b是指数
LL t = 1;
while(b--)
t = (t*a+1)%mod;//求解每一个括号里的数据 重点
res = res*t%mod;//重点
}
cout<<res<<endl;
return 0;
}