【leetcode】Move Zeroes

原创 2016年05月31日 20:23:29

Question

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.

Code

#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[i])//若元素不为0
                swap(nums[j++], nums[i]);
        }
        for (int k = 0; k < nums.size(); k++) {//输出
            cout << nums[k]<<" ";
        }
        cout << endl;
    }
};

int main() {
    Solution so;
    vector<int> nums = { 0,1,0,3,12 };
    so.moveZeroes(nums);
    system("pause");
    return  0;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

leetcode笔记--Move Zeroes

 Move Zeroes 题目:难度(Easy) Given an array nums, write a function to move all 0's to the end of it...

leetcode--Move Zeroes

Given an array nums, write a function to move all 0’s to the end of it while maintaining the relativ...

<LeetCode OJ> 283. Move Zeroes

283. Move Zeroes My Submissions Question Total Accepted: 40008 Total Submissions: 94323 Difficul...

leetcode submission/20161018(move zeroes)

明天发工资啊666 Given an array nums, write a function to move all 0's to the end of it while maintain...

LeetCode之Move Zeroes

1、题目 Given an array nums, write a function to move all 0's to the end of it while maintaining...

(数组)leetcode 283:Move Zeroes

(数组)leetcode 283:Move Zeroes

【LeetCode-283】Move Zeroes(C++)

题目要求:        给出一个数组,要求写一个函数把数组中所有的0全部挪到数组的最后面,同时保持数组中非0元素的顺序不变。比如给出一个数组nums=[0,1,0,3,12]。调用函数之后nums变...

LeetCode Move Zeroes

题目: Given an array nums, write a function to move all 0's to the end of it while maintaining ...

leetcode-283. Move Zeroes c语言

1、来源:点击打开链接 2、题目: Given an array nums, write a function to move all 0's to the end of it while ma...
  • tzh476
  • tzh476
  • 2016年07月20日 07:49
  • 253

[Leetcode 283]Move Zeroes

题目描述: Given an array nums, write a function to move all 0's to the end of it while maintaining th...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:【leetcode】Move Zeroes
举报原因:
原因补充:

(最多只允许输入30个字)