我从网下下的一份华为笔试题大全里的题目:
int A[nSize],其中隐藏着若干0,其余非0整数,写一个函数int Func(int* A, int nSize),使A把0移至后面,非0整数移至
数组前面并保持有序,返回值为原数据中第一个元素为0的下标。(尽可能不使用辅助空间且考虑效率及异常问题,注释规范且给出设计思路)
自己尝试做了下,以下是代码:
#include <iostream>
using namespace std;
/*
* int A[nSize],其中隐藏着若干0,其余非0整数,写一个函数int Func(int* A, int nSize),使A把0移至后面,非0整数移至
* 数组前面并保持有序,返回值为原数据中第一个元素为0的下标。(尽可能不使用辅助空间且考虑效率及异常问题,注释规范且给出设计思路)
*
*/
int Func(int *A, int nSize) {
int index = (nSize - 1);
//由后往前
while ((nSize--) >= 0) {
if (*(A + nSize) == 0) {//为零,直接下标前移
index = nSize;
continue;
}
//否则拿前面的数据与自己相比较
for (int i = 0; i < nSize; i++) {
int last = *(A + nSize);
int pre = *(A + i);
if (pre == 0) {//直接交换,跳出for循环
*(A + nSize) = pre;
*(A + i) = last;
index = nSize;
break;
}
if (last > pre) {//排序交换
*(A + nSize) = pre;
*(A + i) = last;
;//swap
}
}
}
return index;
}
int main(void) {
const int intSize = 10;
int A[intSize] = { 0, 4, 7, 2, 160, 0, 34, 21, 0, 19, 107 };
cout << "The return value= " << Func(&A[0], intSize);
return 0;
}
2010年5月20日更新:
优秀方案:
由第二页Turbo 编写
一个循环就搞掂了.
public static void main(String[] args) {
int[] a = { 0, 4, 7, 2, 160, 0, 34, 21, 0, 19, 107 };
int j = 0;
for (int i = 0; i < a.length; i++) {
if (a[i] == 0 && i != a.length - 1 && a[i + 1] != 0) {
a[j++] = a[i + 1];
a[i + 1] = 0;
}
}
System.out.println(Arrays.toString(a));
}
2010年8月4日更新:
Turbo 的代码确实有问题,如,将数组第一个元素置非1值,结果为[34, 21, 19, 107, 160, 0, 0, 0, 0, 0, 0],显然不对,这是我的审核没到位,感谢liaohui0719提出!
liaohui0719 写道
Turbo的代码有个小瑕疵,若第一个元素不为零,则逻辑会出问题。
应为:
public static void main(String[] args) {
int[] a = { 7, 2, 160,0, 0, 34, 21, 0, 19, 0,0,0,107 };
int j = -1;
for (int i = 0; i < a.length; i++) {
if(j==-1 && a[i]==0)
{
j=i;
}
if (a[i] == 0 && i != a.length - 1 && a[i + 1] != 0) {
a[j++] = a[i + 1];
a[i + 1] = 0;
}
}
System.out.println(Arrays.toString(a));
}