问题:
有一个数组A[nSize],其元素含有多个0,求一函数将所有的非零元素移到前面(不分大小,按原位置前移).并返回非零函数的个数i.
解决方法一:
int get(int *array,int nSize)
{
int temp = 0;
int zeroNum = 0;
for(int i = 0 ; i < nSize ; i ++)
{
if(array[i] != 0)
{
array[zeroNum] = array[i];
if(zeroNum != i)
array[i] = 0;
zeroNum++;
}
}
return zeroNum;
}
解决方法二:
// test060329_1.cpp : Defines the entry point for the console application.
//
#include <iostream>
#include<algorithm>
#include<functional>
using namespace std;
#define MAX_NUM 11
#define TAG INT_MAX
#define F1 1
#define F2 0
#define F3 0
#define F4 0
#define F5 0
#define F6 0
#if F1
int move(int array[], int nSize)//right
{
cout << "f1" << endl;
int temp = 0;
int zeroNum = 0;
int t=0;
for(int i = 0 ; i < nSize ; i ++)
{
if(array[i]==0 || array[i]==TAG)
{
zeroNum++;
for(int j=i+1; j<nSize; j++)
{
if(array[j]!=0 && array[j]!=TAG)
{
array[i] = array[j];
array[j] = TAG;
t++;
break;
}
}
}
}
for(i=0; i<nSize; i++)
{
if(array[i] == TAG)
array[i] = 0 ;
}
return zeroNum - t;
}
#elif F2
int move(int A[],int nSize)//wrong
{
cout << "f2" << endl;
int n,tem,i=0;
for(n=0;n<nSize;n++)
{
if(A[n]==0)
{
tem=A[n];
A[n]=A[n+1];
A[n+1]=tem;
i++;
}
}
return i;
}
#elif F3
int move(int *array,int nSize)//wrong
{
cout << "f3" << endl;
int temp = 0;
int zeroNum = 0;
for(int i = 0 ; i < nSize ; i ++)
{
if(array[i] != 0)
{
array[zeroNum] = array[i];
if(zeroNum != i)
array[i] = 0;
zeroNum++;
}
}
return zeroNum;
}
#elif F4
int move( int A[],int nSize )//fan le
{
cout << "f4" << endl;
return partition( A, A + nSize, bind1st( equal_to<int>(), 0 ) ) - A;
}
#elif F5
int move(int A[], int nSize)//return wrong
{
cout << "f5" << endl;
int i = 0;
int n;
for(n = 0; n < nSize; n++)
{
if(A[n] != 0)
{
A[i] = A[n];
A[n] = 0;
i++;
}
}
return i;
}
#elif F6
void moveAhead(int a[], int from, int size)//return wrong
{
int temp = a[from];
for( ;from < size; from++)
{
a[from]=a[from+1];
}
a[size-1] = temp;
}
int move(int a[], int size)
{
cout << "f6" << endl;
if(size == 0) return 0;
int noZero = 0;
for(int i= 0; i < size; i++)
{
if(a[i] == 0)
{
moveAhead(a,i,size);
size--;
--i;
}
else ++noZero;
}
return noZero;
}
#endif
int main(int argc, char* argv[])
{
int a[MAX_NUM] = {0,0,0,1,55,0,1,1,0,0,0};
for(int i=0; i<MAX_NUM; i++)
cout << a[i] << " ";
cout << endl;
int nZero = move(a,MAX_NUM);
cout << nZero << endl;
for(i=0; i<MAX_NUM; i++)
cout << a[i] << " ";
cout << endl;
return 0;
}
拷进vc运行便是,想运行哪个函数把
#define Fx x
后面的0改成1便是,其他都改0