Move Zeroes


  • 0

    Click here to see the full article post


  • 0
    F

    Python:

    class Solution(object):
        def moveZeroes(self, nums):
            """
            :type nums: List[int]
            :rtype: void Do not return anything, modify nums in-place instead.
            """
    
            count = nums.count(0)
            for i in range(count):
                nums.remove(0)
                nums.append(0)
    

  • 0
    V

    Here is the C# version similar to the idea of soln# 3 above

     public void MoveAllZerosToEnd(int[] arr)
            {
                int write = 0;
                bool isZeroSeen = false;
    
                if (arr == null || arr.Length == 0)
                    throw new ArgumentException("Given array is null");
    
                for (int read = 0; read < arr.Length; read++)
                {
                    if (arr[read] == 0)
                    {
                        if (!isZeroSeen)
                            write = read;
                        
                        isZeroSeen = true;
                    }
                    else if (arr[read] != 0)
                    {
                        if (isZeroSeen)
                        {
                            arr[write++] = arr[read];
                            arr[read] = 0;
                        }
                    }
                }
            }
    

  • 0
    X

    Consider all non-zeros : 1,2,3,4,5
    not need to swap with themselves..

    void moveZeroes_better(vector<int>& nums) {
        size_t insert_pos = 0;
        for (int &e : nums) {
            if (e != 0) {
                if (e != nums[insert_pos])
                    swap(e, nums[insert_pos]);
                ++insert_pos;
            }
        }
    }
    

  • 1

    @xsh6528 Your consideration is good, but actually this will perplex the solution and its performance can be affected due to this further-checking. Readability and performance can be worse.

    class Solution {
    public:
        void moveZeroes(vector<int>& nums) 
        {
            int index = 0;
            for(int i = 0; i < nums.size(); ++i)
            {
                if(nums[i] != 0) 
                    nums[index++] = nums[i];
            }
            fill(nums.begin()+index, nums.end(), 0);
        }
    };
    

  • 0
    public class Solution {
        public void moveZeroes(int[] nums) {
            for(int i = 0;i<nums.length;i++){
                if(nums[i]==0){
                    for (int j=i+1;j<nums.length;j++){
                        if(nums[j]!=0){
                            int temp=nums[i];
                            nums[i]=nums[j];
                            nums[j]=temp;
                            break;
                        }
                    }
                }
            }
        }
    }
    
    

  • 0

    @活泼大汉子 Next time you'd better format your code bracing them between ``` as Markdown does. Now I've done that for you.


  • 0
    H

    Consider all non-zeros : 1,2,3,4,5
    not need to swap with themselves.. (sorry for the last post ...missed format)

    void moveZeroes(vector<int>& nums) {
        for (int lastNonZeroFoundAt = 0, cur = 0; cur < nums.size(); cur++) {
            if (nums[cur] != 0&&lastNonZeroFoundAt==cur) {
                lastNonZeroFoundAt++;
            } else if(nums[cur] != 0&&lastNonZeroFoundAt!=cur){
                swap(nums[lastNonZeroFoundAt++], nums[cur]);
            }
        }
    }
    

  • 0

    @hu26 In your special case, it is no need to swap them all. As my previous post suggested we can just fill the remaining part to make the solution easy enough. Besides the article is just a reference, so try not to be so harsh and serious about it. Okay? You're now kind of too particular about it.


  • 0
    H

    @LHearen Please see my code, in the special case, I didn't swap any elements.!!! And that's the point.! :)


  • 0

    @hu26 But we're not all the time handling your special cases, as for normal cases, your code will require more operations.


  • 0
    B

    My Ruby code. Working fine, but not validated by leetcode.

    Ruby

    def move_zeroes(nums)
    
    @nums = nums.sort!
    
    nums.each do |i|
    		if i == 0
    			nums.push(i, (nums.delete(i)))
    		end
    	end
    	
    end
    

  • 0
    C

    Here is a Java solution, what do you think about it guys. its O(1) in terms of space and O(n) in time

    public void moveZeroes(int[] nums) {
        int zeroCptr = nums.length - 1;
        int[] ans = new int[nums.length];
        for(int i = 0;i<nums.length;i++) {
            if(nums[i] != 0) {
                nums[(nums.length - 1) - zeroCptr] = nums[i];
                zeroCptr--;
            }
        }
        for(int i = nums.length - 1 - zeroCptr;i < nums.length;i++) {
            nums[i] = 0;
        }
    }
    

    }


  • 0

    @codingcoder said in Move Zeroes:

    public void moveZeroes(int[] nums) {
    int zeroCptr = nums.length - 1;
    int[] ans = new int[nums.length];
    for(int i = 0;i<nums.length;i++) {
    if(nums[i] != 0) {
    nums[(nums.length - 1) - zeroCptr] = nums[i];
    zeroCptr--;
    }
    }
    for(int i = nums.length - 1 - zeroCptr;i < nums.length;i++) {
    nums[i] = 0;
    }
    }

    }

    Can be better.


  • 0
    K
    def movezeros(list):
        b=[]
        for i in list:
            if i:
                b.append(i)
        for j in range(0,list.count(0)):
            b.append(0)
        return b
    

  • 0
    C

    My code by use of STL is as follows:

    #include <vector>
    #include <iostream>
    #include <algorithm>
    
    using namespace std;
    
    class Solution {
    public:
        void moveZeroes(vector<int>& nums) {
            
            std::vector<int>:: iterator it = remove(nums.begin(), nums.end(), 0);
            int newLen = distance(nums.begin(), it);
            
            for(int i=newLen; i<nums.size(); i++) {
            	nums.at(i) = 0;
            }
        }
    };
    

  • 1
    K

    My Javascript Solution

       var length = nums.length;
       var i = 0;
       while(i < length){
           var num = nums[i];
           if(num === 0){
               nums.splice(i, 1);
               nums.push(0);
               length--;
           }else{
               i++;   
           }
       }
    };```

  • 0
    A

    Please feel free to comment on this solution. Guess its O(n) -time and O(1) space

    public class Solution {
        public void moveZeroes(int[] nums) {
            int lastZero =-1;
            int temp;
            for(int i=0;i<nums.length;i++){
                if(nums[i] == 0 && (i+1)<nums.length){
                    if(nums[i+1]==0 && lastZero <0){
                        lastZero = i;
                        continue;
                    }
                    else if(nums[i+1]==0){
                        continue;
                    }
                    else if(nums[i+1] !=0 && lastZero >=0){
                        temp = nums[i+1];
                        nums[i+1]=nums[lastZero];
                        nums[lastZero]=temp;
                        lastZero++;
                        continue;
                    }
                    temp=nums[i];
                    nums[i] = nums[i+1];
                    nums[i+1] = temp;
                }
            }
        }
    }
    

  • -1
    S

    public class Solution {
    public void moveZeroes(int[] nums) {
    int zeros = 0; //number of zeros found between numbers
    int numStart = -1; //position of first non-zero number
    int numEnd = -1; //position of first zero after series of non-zero numbers

        for(int i = 0; i < nums.length; i++){
            if(nums[i] == 0){
                zeros++;
                continue;
            }
            if(zeros > 0 && nums[i] != 0){
                numStart = i;
                for(int j = i +1; j < nums.length; j++){
                    if(nums[j] == 0){
                        numEnd = j;
                        i = move(nums,numStart,numEnd,zeros);
                        zeros = 0;
                        numStart = -1;
                        numEnd = -1;
                        break;
                    }
                }
                if(zeros > 0){
                    numEnd = nums.length;
                    i = move(nums,numStart,numEnd,zeros);
                    zeros = 0;
                    numStart = -1;
                    numEnd = -1;
                }
            }
        }
    }
     public int move(int[] array, int start,int end, int z){
            int newPos = start;
            for(int i = start ; i < end; i++){
                newPos = i -z;
                array[newPos] = array[i];
                array[i] = 0;
            }
            return newPos;
        }
    

    }


  • -1
    J

    This is my C++ code:

    class Solution 
    {
    public:
        void moveZeroes(vector<int>& nums) 
    	{
    	        int len=nums.size();
    		for(int j=0,ci=0;ci<len;ci++)
    		{
    			if(nums[j]==0)
    			{
    				nums.erase(nums.begin()+j);
    				nums.push_back(0);
    				j--;
    			}
    			j++;
    		}		
           }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.