leetcode刷题日记——Move Zeroes

来源:互联网 发布:很臭的东西淘宝有卖吗 编辑:程序博客网 时间:2024/05/20 09:43
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 size=nums.size();        if(size==0) return;        for(int i=size-1;i>0;i--){            if(nums[i]==0) continue;            for(int j=0;j<i;j++){                if(nums[j]==0){                    nums[j]=nums[j+1];                    nums[j+1]=0;                }            }        }   }};

虽然通过了,但是考虑到题目中的另外一个要求,最小化交换次数,而我们知道的冒泡排序中需要做大量的两两交换,因此不是最优的解法。再细看此题分析,我们可以先把非零元素挑出来按序放到数组前面,然后对于后面剩下的位置,自动补零就可以了,这样既避免了大量的交换,并且运算时间复杂度也从O(n*n)降到了O(n),具体实现如下

class Solution {public:    void moveZeroes(vector<int>& nums) {       int size=nums.size();       if(size==0) return;       int index=0;       for(int i=0;i<size;i++){           if(nums[i]!=0)              nums[index++]=nums[i];       }       for(int i=index;i<size;i++){           nums[i]=0;       }    }};


0 0
原创粉丝点击