美文网首页
编程算法练习

编程算法练习

作者: 吸霾少年 | 来源:发表于2017-09-25 19:50 被阅读0次

1 移动零

/*
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.
 
Notice
1. You must do this in-place without making a copy of the array.
2. Minimize the total number of operations.
 
Example
Given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].
*/
// Example program
#include <iostream>
#include <vector>

void ZerosMoves(std::vector<int>& nums) {
    std::vector<int>::iterator it1, it2;
    it1 = it2 = nums.begin();
    while (it1 != nums.end()) {
        if (*it1 == 0) {
            it1++;
        } else if (it1 != it2) {
            std::swap(*(it1++), *(it2++));
        } else {
            it1++;
            it2++;
        }
    }
}
int main()
{
    int array[5] = {0,1,0,3,12};
    std::vector<int> nums(array, array + 5);
    ZerosMoves(nums);
    for(int val:nums) {
        std::cout << " " << val;
    }
}

相关文章

网友评论

      本文标题:编程算法练习

      本文链接:https://www.haomeiwen.com/subject/mfwdextx.html