Move Zeroes

来源:互联网 发布:弱电网络系统图 编辑:程序博客网 时间:2024/05/16 10:03

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:

  1. You must do this in-place without making a copy of the array.
  2. Minimize the total number of operations.
分析:看到这个题,没有多想就写除了下面这个代码
class Solution {public:    void moveZeroes(vector<int>& nums) {        int n = nums.size();        int i, j;        for(i = 0; i < n; i++){            if(nums[i] != 0){                for(j = 0; j < i; j++){                    if(nums[j] == 0) {                        int temp = nums[j];                        nums[j] = nums[i];                        nums[i] = temp;                    }                }            }        }    }};

功能是实现了,但是看到执行时间的排行。感觉果然是思考题目用的时间少了,写出来的代码执行时间(288ms)就很长,,,
所以下来思考了一下下,发下这个题目其实是和之前自己博客里面的那些Remove Duplicates from Sorted Array这个是很类似的,不要受题目的影响就在想着交换元素,先把0当做要移除的元素,这就可以借鉴之前的算法思路了,然后移动完成之后,在再数组后面全部添加上0就可以了,,,
结果最终代码就成了这样子了,代码执行时间(20ms)
class Solution {public:    void moveZeroes(vector<int>& nums) {        int n = nums.size();        int i;        int j = 0;        for(i = 0; i < n; i++){            if(nums[i] != 0) nums[j++] = nums[i];        }        while(j < n)        nums[j++] = 0;    }};

看来还是功力尚欠,没能第一时间借鉴到以前的思路抓狂
0 0