p48 moved backward zero (leetcode 283)

A: problem-solving ideas

Method a: Method using the cursor speed, slow pointer on the insertion position of nonzero elements, fast cursor points nonzero elements. If the cursor is quick to point zero elements, then move back one, or else assign fast cursor is pointing element to element slow cursor is pointing.

Method two: the cursor speed using the same method, when the cursor points fast zero elements when a position moved rearwardly directed face when not zero elements, and mutual exchange element slow cursor pointing.

Time above-described two methods: O (n), Space: O (1)

Two: Complete code examples (C ++ version and the Java version)

Method one C ++:

class Solution 
{
public:
    void moveZeroes(vector<int>& nums) 
    {
        if (nums.size() == 0) return;
        int slow = 0;

        for (int fast = slow; fast < nums.size(); fast++)
        {
            if (nums[fast] != 0)
            {
                nums[slow++] = nums[fast];
            }
        }

        while (slow < nums.size())
        {
            nums[slow++] = 0;
        }
    }
};

Method One Java:

class Solution 
{
    public void moveZeroes(int[] nums) 
    {
          if(nums==null||nums.length==0) return;
          int slow=0;
          
          for(int fast=slow;fast<nums.length;fast++)
          {
              if(nums[fast]!=0)
              {
                  nums[slow++]=nums[fast];
              }
          }
          
          while(slow<nums.length)
          {
              nums[slow++]=0;
          }
    }
}

Method Two C ++:

class Solution {
public:
    void swap(int& a, int& b) { int c = a; a = b; b = c; }

    void moveZeroes(vector<int>& nums) 
    {
        if (nums.size() == 0) return;
        int slow = 0;

        for (int fast = slow; fast < nums.size(); fast++)
        {
            if (nums[fast] != 0)
            {
                swap(nums[slow++],nums[fast]);
            }
        }
    }
};

Method Two Java:

class Solution
{
    public void moveZeroes(int[] nums)
    {
          if(nums==null||nums.length==0) return;
          int slow=0;
          
          for(int fast=slow;fast<nums.length;fast++)
          {
              if(nums[fast]!=0)
              {
                  int temp=nums[fast];
                  nums[fast]=nums[slow];
                  nums[slow]=temp;
                  slow++;
              }
          }
    }
}

 

Guess you like

Origin www.cnblogs.com/repinkply/p/12511726.html