1. 曾经面试的时候被问到一个天,就是将一个整形数组中的偶数全部放在前面,而且要保持之前的相对顺序,要求时间和空间复杂度最小
#include<iostream>
#include<time.h>
using namespace std;
void even_num_first(int a[], int n)
{
for(int i = 0, j = 0; i < n; i++)
{
if(a[i] % 2 == 0)
{
int t = a[j];
a[j] = a[i];
a[i] = t;
j++;
}
}
}
int main()
{
srand(time(NULL));
int a[10] = {0};
for(int i = 0; i < 10; i++)
{
a[i] = rand() % 10;
cout<<a[i]<<' ';
}
cout<<endl;
even_num_first(a, sizeof(a)/sizeof(a[0]));
for(int j = 0; j < 10; j++)
{
cout<<a[j]<<' ';
}
cout<<endl;
return 0;
}
#include<iostream>
using namespace std;
int main()
{
int b[10] = {1,2,3,4,2,5,6,7,8,9};
int a[10000] = {0};
for(int i = 0; i < 10; i++)
{
a[b[i]] += 1;
if(a[b[i]] >= 2)
{
cout<<a[b[i]]<<endl;
break;
}
}
return 0;
}
3.一个整形数组int a[100] 保存1-100 现在随机将其中两个数改为0, 找出这两个数,要求时间和空间复杂度尽量小
#include<iostream>
#include<algorithm>
#include<time.h>
using namespace std;
int main()
{
srand(time(NULL));
int a[10] = {2,1,3,4,6,5,7,8,9,10};
int k1 = rand()%10;
int k2 = rand()%10;
while(k1 == k2)
{
k2 = rand()%10;
}
cout<<"delete "<<a[k1]<<','<<a[k2]<<endl;
a[k1] = 0;
a[k2] = 0;
sort(a, a+10);
if(a[9] != 10)
cout<<10<<endl;
if(a[9] != 10 && a[8] == 9)
cout<<9<<endl;
for(int i = 0; i < 9; i++)
{
if(a[i+1] - a[i] == 3)
{
cout<<a[i+1]-1<<endl;
cout<<a[i+1]-2<<endl;
break;
}
else if (a[i+1] - a[i] == 2)
{
cout<<a[i+1]-1<<endl;
}
}
return 0;
}