注:机试以解题为主,优化其次
快速排序
int partition(int a[], int low, int high){
int pivot = a[low];
while (low <= high){
while (a[high] > pivot && low <= high) high -- ;
a[low] = a[high];
while (a[low] < pivot && low <= high ) low ++ ;
a[high] = a[low];
}
a[low] = pivot;
return low;
}
二分
int l = 0, r = n - 1;
while (l < r){
int mid = r + l >> 1;
if (a[mid] >= x) r = mid;
else l = mide + 1;
}
while (l < r){
int mid = r + l + 1 >> 1;
if (a[mid] <= x) l = mid;
else r = mid - 1;
}
前缀和
int a[N];//保存每个元素的值
for (int i = 1; i <= n; i ++ ) s[i] = s[i - 1] + a[i];
int s[N];//元素值和前缀和用一个数组保存
for (int i = 2; i <= n; i ++ ) s[i] += s[i - 1];
//从第r个数到第l个数的区间和为 s[l] - s[r - 1]
双指针
//可利用计数数组来记录元素出现的次数
//利用快指针和慢指针
关于二进制
int lowbit(int x){
return x & -x; //返回x的二进制表示中最低位1出现的位置
}
void bit1(int x) //输出某数的二进制表示
{
int b = x;
while (b >= 1)
{
p[i] = x >> i & 1;
b = b >> 1;
i++;
}
for (int j = i - 1; j >= 0; j--)
cout << p[j];
}
进制转换
int main(){
cin >> x;
stack<int> s;
if (x == 0) cout << 0;
else {
while (x){
s.push(x % n); //n表示的是转换为n进制
x /= n;
}
}
while (!s.empty()){
cout << s.top();
s.pop();
}
}