Its cool problem.
Method 1)
Count the number of 1's (ones) in the array , say k.
Then simply set last k elements to 1 and n-k elements to 0(zero).
(other way is count 0's)
Its takes total (n+ n = 2n) = O(N) time.
Method 2)
f = 0;
l = n -1;
for ( ; f < l; ) {
if(arr[f]) {
if(!arr[l]) {
arr[f++]=0;
arr[l]=1;
}
l--;
} else {
arr[l] && l--;
f++;
}
}
Let me know which is better ?? And if there is any better approach..
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment