I am an active software engineer.
Wednesday, May 15, 2013
Move zeros to end C++
Given an unsorted integer array, place all zeros to the end of the array without changing the sequence of non-zero elements. (i.e. [1,3,0,8,12, 0, 4, 0,7] --> [1,3,8,12,4,7,0,0,0])
思路:用个index记录当前需要填充的位置,扫一遍就行了,跟quicksort思路一致。复杂度O(n)
void
pushzeros(
int
A[],
int
n){
int
index = 0;
for
(
int
i = 0; i < n; i++){
if
(A[i] != 0){
int
tmp = A[index];
A[index++] = A[i];
A[i] = tmp;
}
}
}
No comments:
Post a Comment
Newer Post
Older Post
Home
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment