leetcode:Move Zeros

题目:

给定一个数组nums,写一个函数,将数组中所有的0挪到数组的末尾,⽽维持其他所有非0元素的相对位置。
举例: nums = [0, 1, 0, 3, 12],函数运⾏后结果为[1, 3, 12, 0, 0]。

解法一:

创建一个临时数组,将原数组中的不为0元素存放到临时数组中。再将临时数组中的所有元素赋给原始数组,原始数组中其他元素置0.
代码:

class Solution{
public:
    void moveZeroes(vector<int>& nums){
        vector<int>nonZeroesElements;
        //move all the non not zero elements to the nonZeroesElements array
        for(unsigned i=0;i<nums.size();i++){
            if(nums[i]){
            nonZeroesElements.push_back(nums[i]);
            }
      }
       //move all the elements of nonZeroesElements to nums
            for(int i=0;i<nonZeroesElements.size();i++){
                    nums[i] = nonZeroesElements[i];
            }
        //the rest elements have to be set as 0
        for(int i=nonZeroesElements.size();i<nums.size();i++){
            nums[i] = 0;
        }
    }
};

时间复杂度:O(n)
空间复杂度:O(n)

解法二:

设置一个临时变量K,用来指向非0元素在数组中所要存放的位置,K初始化为0。遍历数组,当nums[i]非0,则nums[k] = nums[i],k++,继续遍历数组。解法二和解法一雷同,只是将解法一中的临时数组取消,直接在原数组进行改动,这样更省空间。
代码

//second method
    void moveZeroes2(vector<int>&nums){
        //use a temp element k that points to the location
        //where not zero element will place
        int k = 0;

        for(int i=0;i<nums.size();i++){//nums[0~k] place all the not zero element
            if(nums[i]){//nums[i] is not zero
                nums[k] = nums[i];
                k++;
            }
        }
        //in the array a, other elements have to be set as zero
        for(int i=k;i<nums.size();i++){
            nums[i] = 0;
        }
    }

时间复杂度:O(n)
空间复杂度:O(1)

解法三

创建一个临时变量k, k初始化为0. 遍历数组nums, nums[i]非0,交换nums[i]和nums[k],最后效果nums[0~k]皆非0,nums[k+1 ~ size-1]元素皆为0. 与上述两种方法的区别是,通过将元素进行了交换,而不是用非0元素直接覆盖原值,后续不需置0。
代码

//third method
    void moveZeroes3(vector<int>& nums){
        int k = 0;//nums[0~k] are not zero

        for(int i=0;i<nums.size();i++){
            if(nums[i]){//nums[i] is not zero
                if(k!=i){
                    swap(nums[k],nums[i]);//swap nums[i] with nums[k]
                    k++;
                }
                else{
                    k++;//there is no need to swap
                    //at the same position with a not zero element
                }
            }
        }

    }

时间复杂度:O(n)
空间复杂度:O(1)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值