Facebook Phone Interview -- Move Zeros to Right (Easy)
2016-03-23 07:13
288 查看
March 22th, 2016.
Move Zeros to the right end but keep the order of non-zero numbers.
Move Zeros to the right end but keep the order of non-zero numbers.
#include <stdio.h> #inlcude <iostream> #include <vector> using namespace std; // move Zeros to the right end of the array. // classical two pointers problem. void moveZeroToRight(vector<int>& array) { if(array.size() <= 1) return; // if the array only has 0-1 values, no need to sort. int left = 0; // one pointer to remember the left copy. int i = 0; // one pointer to loop the array. while(i < array.size()) { if(array[i] != 0) { array[left++] = array[i++]; // if it is not zero, copy it to the left end. } else { i++; // otherwise, i pointer keeps on moving. } } // copy all non-zeros to the left now. But we need to remember to set the left values to 0. while(left < array.size()) { array[left++] = 0; } } // the following is for test purpose. void printArray(vector<int> array) { for(int i = 0; i < array.size(); ++i) { printf("%d\n", array[i]); } } int main(void) { vector<int> array; array.push_back(0); array.push_back(1); moveZeroToRight(array); printArray(array); }
相关文章推荐
- 嵌入式编程基础知识学习(1)
- 被解放的姜戈08 远走高飞
- Spring源码之bean的加载(三)从bean中获取对象
- Spring源码之bean的加载(二)获取单例bean
- Spring源码之bean的加载(一)
- 【杭电oj】2045 - 不容易系列之(3)—— LELE的RPG难题(递推)
- HoloLens开发手记-全息Hologram
- Raspkate - 基于.NET的可运行于树莓派的轻量型Web服务器
- CSS魔法堂:深入理解line-height和vertical-align
- 理解 virbr0 - 每天5分钟玩转 OpenStack(11)
- 理解 virbr0 - 每天5分钟玩转 OpenStack(11)
- 战火引擎~完爆cocos2d
- Visibility of Point Cloud
- go语言闭包,匿名函数,变量使用
- 简单深刻:为控件创建MouseEnter和MouseLeave事件(覆盖WndProc,增加对消息的处理,真简单!)——连对CM_MOUSEENTER的消息处理都是颇有深意啊!
- bzoj 4066: 简单题
- bzoj 3993: [SDOI2015]星际战争
- bzoj 3611: [Heoi2014]大工程
- bzoj 3530: [Sdoi2014]数数
- LeetCode Count of Smaller Numbers After Self