打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
283 [LeetCode] Move Zeroes 移动零

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.

 

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

 

这道题让我们将一个给定数组中所有的0都移到后面,把非零数前移,要求不能改变非零数的相对应的位置关系,而且不能拷贝额外的数组,那么只能用替换法in-place来做,需要用两个指针,一个不停的向后扫,找到非零位置,然后和前面那个指针交换位置即可,参见下面的代码:

 

解法一:

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++]);            }        }    }};

 

解法二:

class Solution {public:    void moveZeroes(vector<int>& nums) {        int left = 0, right = 0;        while (right < nums.size()) {            if (nums[right]) {                swap(nums[left++], nums[right]);            }            ++right;        }    }};

 

参考资料:

https://leetcode.com/discuss/59064/c-accepted-code

https://leetcode.com/discuss/70169/1ms-java-solution

 

LeetCode All in One 题目讲解汇总(持续更新中...)

分类: LeetCode

自己做的方法:
我的思路是这样的:
第一步:如果第一个位置是0,那么交换位置,一直交换到数组的最后一个位置。
第二部:如果第二个位置是0,那么交换位置,一直交换到数组的最后一个位置。
这样的话,稍微改下冒泡法 就可以了。
这个思路,有点凑巧的意思。数组的最后位置肯定是0 ,交换不交换都一样。

public class Solution {
    public void MoveZeroes(int[] nums) {
        
        for(int i=0;i<nums.Length;i++)
        {
            for(int j=i+1;j<nums.Length;j++)
            {
                if(nums[i]==0)
                {
                    int temp=nums[i];
                    nums[i]=nums[j];
                    nums[j]=temp;
                    
                }
            }
        }
    }
}



本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
480,移动零,通过一个精彩的故事告诉你怎么解
数组
0189. Rotate Array (E)
【原创】90%的人都不会做的一道笔试题
java中的基本算法
2.4 数组
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服