版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xiangxianghehe/article/details/81781273
一.算法题:一个整数数组,设计方法,让所有奇数在前,所有偶数在后。
#include <iostream>
#include <assert.h>
#include <algorithm>
using namespace std;
void swapIntArr(int *an, int n)
{
assert(NULL !=an);
int *p1=an, *p2=an+n-1;
while (p1 < p2)
{
while (*p1 %2 !=0)
{
p1++;
}
while (*p2 %2 == 0)
{
p2--;
}
int t=*p1;
*p1=*p2;
*p2=t;
p1++;
p2--;
}
}
int main()
{
int an[]={3,5,2,5,2,6,8,3,25,65,67,78,34,2,32,3};
int n=sizeof(an)/sizeof(int);
swapIntArr(an,n);
for(int i = 0; i< n;i++)
{
cout <<an[i]<<",";
}
return 0;
}
二.一个乱序数组a[0…n-1],求任意两个元素之间的最大差值
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
const int len=5;
int a[len]={8,2,10,3,9};
int dp[100];
memset(dp,0,sizeof(dp));
//len>=2, so dp[1]=a[1]-a[0], dp[0] doesn't exist!
dp[1]=a[1]-a[0];
for(int i=2;i<len;i++)
{
if(dp[i-1] <= 0)//a[i] is the min
dp[i]=a[i]-a[i-1];
else
dp[i]=dp[i-1]+a[i]-a[i-1];
}
int max=0x80000000;
for(int i=1;i<len;i++)
if(dp[i]>max)
max=dp[i];
cout<<max<<endl;
return 0;
}