leecode 解题总结:283. Move Zeroes
来源:互联网 发布:股票看行情软件 编辑:程序博客网 时间:2024/06/06 01:33
#include <iostream>#include <stdio.h>#include <vector>#include <string>using namespace std;/*问题: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.For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].Note:You must do this in-place without making a copy of the array.Minimize the total number of operations.分析:从后向前,每次找到0,然后就将其后面部分每个元素都前移一位,将该0放到最后位置。这样带来的问题是最前面的0被移动到最后,也可以,也就是所有0的位置是逆置的,然后最后把0的部分逆置一下即可。输出0的总个数num,则从n-1~n-num处的0逆置一下如果从前向后,每次找到0,就把该0移动到最后,这样是可以的,时间复杂度:O(n^2)输入:50 1 0 3 12111020 0输出:1 3 12 0 0100 0关键:1 从后向前,每次找到0,然后就将其后面部分每个元素都前移一位,将该0放到最后位置。这样带来的问题是最前面的0被移动到最后,也可以,也就是所有0的位置是逆置的,然后最后把0的部分逆置一下即可。输出0的总个数num,则从n-1~n-num处的0逆置一下*/class Solution {public: void moveZeroes(vector<int>& nums) { //从后向前,每次找到0,就将后面部分前移一位if(nums.empty()){return;}int count = 0;int size = nums.size();for(int i = size - 1 ; i >= 0 ; i--){if(0 == nums.at(i)){count++;//开始移动位置: i+1~size-1都向前移动for(int j = i + 1 ; j <= size - 1 ; j++){nums.at(j-1) = nums.at(j);}//将0放在最后nums.at(size - 1) = 0;}}//接下来就是逆置最后的0,reverse(nums.begin() + size - count , nums.end()); }};void print(vector<int>& result){if(result.empty()){cout << "no result" << endl;return;}int size = result.size();for(int i = 0 ; i < size ; i++){cout << result.at(i) << " " ;}cout << endl;}void process(){ vector<int> nums; int value; int num; Solution solution; vector<int> result; while(cin >> num ) { nums.clear(); for(int i = 0 ; i < num ; i++) { cin >> value; nums.push_back(value); } solution.moveZeroes(nums); print(nums); }}int main(int argc , char* argv[]){process();getchar();return 0;}
0 0
- leecode 解题总结:283. Move Zeroes
- leecode 解题总结:73. Set Matrix Zeroes
- [leetcode] 283. Move Zeroes 解题报告
- 【LeetCode】283.Move Zeroes解题报告
- [Leetcode] 283. Move Zeroes 解题报告
- 【LeetCode】Move Zeroes 解题报告
- 景岁的Leetcode解题报告:283. Move Zeroes(Python)
- 283.Move Zeroes
- 283. Move Zeroes
- 283. Move Zeroes
- 283. Move Zeroes
- 283. Move Zeroes
- 【LeetCode】283. Move Zeroes
- 283. Move Zeroes
- 283. Move Zeroes
- Leetcode 283. Move Zeroes
- 283. Move Zeroes
- LeetCode #283. Move Zeroes
- SessionFactory的创建方式
- Python 异常(Exception)
- 单例模式之懒汉的并发问题,只需要添加一个 synchronized 就可以解决了
- 欢迎使用CSDN-markdown编辑器
- HDU-6016 count the sheep
- leecode 解题总结:283. Move Zeroes
- Linux系统从零到高手的进阶心得
- 自学笔记一:C#语法基础 类
- PHP+JavaScript 实现图片无刷新上传
- mssql从入门到';drop table --
- 类似QQ控件动态输入框
- xcache 的安装及配置文件参数解释
- zoj 3279 ants 线段树+单点更新+查询下标
- LeetCode之路——Reverse Integer