Facebook interview - Move all zeroes to end of array

Given an array of random numbers, Push all the zero’s of a given array to the end of the array. For example, if the given arrays is {1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0}, it should be changed to {1, 9, 8, 4, 2, 7, 6, 0, 0, 0, 0}. The order of all other elements should be same. Expected time complexity is O(n) and extra space is O(1).

 

Solution 1:

It rerains ordering.

// move all zeros to end of array, keep the non-zero elements order
public static void moveZeroToEnd(int[] A) {
	int n = A.length, cnt = 0;
	for(int i=0; i<n; i++) {
		if(A[i] != 0) {
			A[cnt++] = A[i];
		}
	}
	while(cnt < n) {
		A[cnt++] = 0;
	}
}

 

Solution 2:

It does not keep the non-zero elements order.

// move all zeros to end of array, does not keep the non-zero elements order
public static void moveZeroRight(int[] A) {
	for(int i=0, j=A.length-1; i<j; i++) {
		if(A[i] == 0) {
			while(j>i && A[j] == 0) j--;
			swap(A, i, j);
		}
	}
}

private static void swap(int[] A, int i, int j) {
	int tmp = A[i];
	A[i] = A[j];
	A[j] = tmp;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值