双指针算法
利用单调关系,将O(n2)算法转变为O(n)
#include <bits/stdc++.h>
using namespace std;
const int N = 100000;
int a[N], s[N];
int main()
{
int n;
cin >> n;
for (int i = 0; i < n; i++)
scanf("%d", &a[i]);
int res = 0;
for (int i = 0, j = 0; i < n; i++)
{
s[a[i]]++;
while (s[a[i]] >= 2)
{
s[a[j]]--;
j++;
}
res = max(res, i - j + 1);
}
cout << res << endl;
system("pause");
return 0;
}
#include <bits/stdc++.h>
using namespace std;
const int N = 100010;
int main()
{
int n, m, x;
int a[N], b[N];
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 (a[i] + b[j] == x)
{
printf("%d %d\n", i, j);
break;
}
}
system("pause");
return 0;
}
位运算
若想取x二进制中第k位的数字 x >> k & 1 即可
#include <bits/stdc++.h>
using namespace std;
int lowbit(int x);
int main()
{
int n;
scanf("%d", &n);
int x[100010];
for (int i = 0; i < n; i++)
{
scanf("%d", &x[i]);
int res = 0;
while (x[i])
{
x[i] -= lowbit(x[i]);
res++;
}
printf("%d ", res);
}
system("pause");
return 0;
}
int lowbit(int x)//返回该数二进制表示的第一个1及它之后的所有0
{
return x & -x;
}