移动零

给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。

示例:
输入: [0,1,0,3,12]
输出: [1,3,12,0,0]


说明:

1.必须在原数组上操作,不能拷贝额外的数组。
2.尽量减少操作次数。


解法1:(自己的做法)

分三步:一:先统计有多少个非零数count。二:把count个非零数提到数组前面(i指针定位前面位置,j指针则遍历后面元素,遇到非零数就把它和nums[i]交换,且i++.重复上述操作,把所有非零数放到前面去)。三:把数组中剩余位置元素置0.

java:
class Solution {
    public void moveZeroes(int[] nums) {
        int n=nums.length;
        int count =0;
        for(int i=0;i<n;i++){
            if(nums[i]!=0){
                count+=1;
            }
        }

        for(int i=0;i<count;i++){
            if(nums[i]==0){
                 int j=i+1;
                 while(nums[j]==0&&j<n-1){
                     j++;
                 }
                nums[i]=nums[j];
                nums[j]=0;
            }
        }

        for(int i=count;i<n;i++){
            nums[i]=0;
        }


    }
}
解法1进阶版:

这是我在csdn上看到的大佬的做法,感觉我的思路跟他的一样,但大佬的代码简洁了许多。

 void moveZeroes(vector<int>& nums) {
        // Write your code here
        int pos1 = 0;
        int n = nums.size();
        for(int i=0; i<n; i++)
        {
            if(nums[i] != 0)
            {
              if(i != pos1)
                 nums[pos1] = nums[i];
              pos1++;
            }
        }

        for(int i=pos1; i<n; i++)
             nums[i] = 0;
    }
};
解法1又进阶版:

思路一样,也是学习大佬的做法,代码是真的简洁!

class Solution {
public:
    void moveZeroes(vector<int>& nums) {
        for (int i = 0, j = 0; i < nums.size(); ++i) {
            if (nums[i]) {
                swap(nums[i], nums[j++]);
            }
        }
    }
};
解法2:

思路有所不同,两个索引i和j,i从后往前遍历,遇到零算出i和j的差值,然后把后面的元素前移。貌似这样做移动的步骤有点多。

public void moveZeroes(int[] nums) {
    int curIndex = nums.length - 1;
    int lastIndex = nums.length - 1;
    int count = 0;

    while (curIndex >= 0) {
        if (nums[curIndex] == 0) {
            count = lastIndex - curIndex;
            for (int i = 0; i < count; i++) {
                nums[curIndex + i] = nums[curIndex + i + 1];
            }
            nums[lastIndex] = 0;
            lastIndex--;
        }
        curIndex--;
    }
}

BB一句:

简洁!!简洁!!学习!!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值