将数组中的所有零移到数组末尾-代码实例

  电面Bloomberg被问到算法的一个问题:将数组中的所有零移到数组末尾。

  当时给了一个naive algorithm: 遍历整个数组,Detect到0然后就将0移动到最末尾,然后不断将后面的数向前移动。这个方法可行,但依次移动数组内部的内容很费操作数,并且当数组中有很多0的时候,这个方法就特别的低效率。

  在电面后想到,为什么不直接移动非0的数!

  优化算法:遍历数组,初始化count=0,count依次记录非0的个数,检测到一个非0数就将其存入array[count]中,然后从array[count]开始输出0直到数组末尾。

  

//
//crackCoding
//

#include <iostream>
using namespace std;

void moveZeroToTheEnd(int [], int);


int main(){
    //Array Example
    const int numItems=10;
    int array[numItems]={0,2,3,0,0,1,0,5,2,0};
    
    moveZeroToTheEnd(array, numItems);
    
    //Print out the result
    for (int i=0; i<numItems; ++i) {
        cout<<array[i]<<" ";
    }
}

void moveZeroToTheEnd(int array[], int numItems){
    int count=0;
    
    for (int i=0; i<numItems; ++i) {
        if (array[i]!=0) {
            array[count++]=array[i];
        }
    }
    
    //Fill the left of the array to 0
    for (int j=count;j<numItems; ++j) {
        array[j]=0;
    }
}

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值