作者: admin, 讨论版: 算法集锦, 发表时间: 2015-03-05 02:23:21 PST
标题: Separate 0s and non-0s
关键字: Array MS
Given an array of integers, {1,0,2,0,3,0,0,4,5,6,7,0,0,0}, you have to create a new array which will be like (1,2,3,4,5,6,7,0,0,0,0,0,0,0}, without using any other temporary array.
From: here.
-- solution --
#include <iostream>
using namespace std;
// This works.
void sep(int A[], int n) {
if (n <= 1) return;
int k = 0; // pos of non-zero
for (int i = 0; i < n; ++ i) {
if (A[i] != 0) {
A[k] = A[i];
if (k != i) A[i] = 0;
++ k;
}
}
}
void dump(int A[], int n) {
for (int i = 0; i < n; ++ i) {
if (i > 0) cout << ", ";
cout << A[i];
}
cout << endl;
}
int main() {
int A[] = {1,0,2,0,3,0,0,4,5,6,7,0,0,0};
int n = sizeof(A) / sizeof(int);
dump(A, n);
sep(A, n);
dump(A, n);
}
--
最后修改: admin on 2015-03-05 02:23:47 PST
※ 来源: homecox.com [来自: 72.]
|
|
|