分享

283 [LeetCode] Move Zeroes 移动零

 雪柳花明 2016-09-22

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:///discuss/59064/c-accepted-code

https:///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;
                    
                }
            }
        }
    }
}



    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多