283. Move Zeroes
2016-05-13 14:46
309 查看
283. Move Zeroes
Description:Given an array nums, write a function to move all 0 ‘s to the end of it while maintaining the relative order of the non-zero elements.
note:
1. You must do this in-place without making a copy of the array.
2. Minimize the total number of operations.
Example:
For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].
Hint:
Link:
https://leetcode.com/problems/move-zeroes/
Analysis:
1.首先注意要求,必须在原数组内完成任务,不能通过复制来完成。
2.刚开始面对这个问题,首先想的是怎么把0 都一个个挪到数组尾部,随便找了几个数尝试了一下,当多个0 出现时你会发现这是件很麻烦的事儿。
3.然后想到可能把非0 的数挪到前边,然后在末尾全补为0。尝试了一下,发现这样果然非常方便。
Source Code(C++):
#include <iostream> #include <vector> using namespace std; class Solution { public: void moveZeroes(vector<int>& nums) { int j=0; for (int i=0; i<nums.size(); i++) { if (nums.at(i)!=0) { nums.at(j++)=nums.at(i); } } for(int i=j; i<nums.size(); i++) { nums.at(i)=0; } } }; int main() { Solution s; vector<int> nums; nums.push_back(0); nums.push_back(1); nums.push_back(0); nums.push_back(3); nums.push_back(12); s.moveZeroes(nums); for (int i=0; i<nums.size(); i++) { cout << nums.at(i) << endl; } return 0; }
相关文章推荐
- android开源框架android-async-http使用
- 基于centos6.7的Ceph分布式文件系统安装指南
- [The Hacker Playbook] 4.THE LATERAL PASS - MOVING THROUGH THE NETWORK
- linux socket 客户端和服务器端 基础框架代码
- C++智能指针详解
- 数组中的逆序对
- gcc/g++/ldd等常用命令基本参数(整理)
- 常用Meta整理
- nodejs连接mongodb的方法
- RabbitMQ Server的安装、配置及常用命令
- hdu 4496(并查集的边删除)
- 线性代数中向量、矩阵深度理解(PartI)
- 关于oracle实例即localhost:1521/orcl中的orcl
- 论Android网络请求库——android-async-http
- 数据库应用软件
- Android通知代码
- HDU 2089 不要62 数位dp
- webService 客户端接口调用【java】
- Android Studio使用gradle打包指定包名和类的jar
- mysql Sort aborted: Out of sort memory, consider increasing server sort buffer size的解决方法