手机网站开发服务seo按照搜索引擎的
目录
双指针算法
最长连续不重复子序列
数组元素的目标和
双指针算法
常见的两种样式:
-
双指针指向两个不同的区间
-
双指针指向一个区间的左右两端,这种方式更加常见
双指针算法思想
for(int i=0;i<n;i++)for(int j=0;j<n;j++)O(n^2) 时间复杂度
我们要把这个思想优化,一般利用一些单调性的方式
需求 asd qwe zxc 去掉空格,每个字符串单独一行
要求输出:
asd
qwe
zxc#include<iostream>
#include<string.h>using namespace std;int main()
{char str[100];gets(str);int n = strlen(str);for(int i=0;i<n;i++){int j=i;while(j<n && str[i]!=" ") j++;for(int k=i;k<j;k++) cout<<str[k];cout<<endl;//令i直接移到j的位置,利用的是发现题目中单调性来优化,降低时间复杂度i=j;}return 0;
}
双指针算法模板
for(int i=0,j=0;i<n;i++)
{while(j<i && check(i,j)) j++;//每道题目的具遗体逻辑
}for循环遍历i,while依据题意定下j停下的位置,之后题目的具体代码,之后利用i,j之间关系进行优化
最长连续不重复子序列
解题代码
#include <iostream>using namespace std;const int N = 100010;int n;
int q[N], s[N];int main()
{scanf("%d", &n);for (int i = 0; i < n; i ++ ) scanf("%d", &q[i]);int res = 0;for (int i = 0, j = 0; i < n; i ++ ){s[q[i]] ++ ;while (j < i && s[q[i]] > 1) s[q[j ++ ]] -- ;res = max(res, i - j + 1);}cout << res << endl;return 0;
}
数组元素的目标和
解题代码
#include <iostream>using namespace std;const int N = 1e5 + 10;int n, m, x;
int a[N], b[N];int main()
{scanf("%d%d%d", &n, &m, &x);for (int i = 0; i < n; i ++ ) scanf("%d", &a[i]);for (int i = 0; i < m; i ++ ) scanf("%d", &b[i]);for (int i = 0, j = m - 1; i < n; i ++ ){while (j >= 0 && a[i] + b[j] > x) j -- ;if (j >= 0 && a[i] + b[j] == x) cout << i << ' ' << j << endl;}return 0;
}