Simple Solution beats 95% submissions


  • 0
    R
    class Solution {
    public:
        void moveZeroes(vector<int>& nums) {
            int l=0, r=0;
            int len = nums.size();
            
            /* Look for the first zero and initialize l, r to it.  */
            while(nums[l] != 0 && l < len) {
                l++;
            }
            r = l;
            
            while(r < len) {
                /* Look for next non-zero and copy that to lth position, increament l */
                if(nums[r] != 0) {
                    nums[l] = nums[r];
                    l++;
                }
                    
                r++;
            }
            
            /* Copy zero at remaining positions */
            while(l<len) {
                nums[l] = 0;
                l++;
            }
        }
    };

  • -1
    J
    public class Solution {
    public void moveZeroes(int[] nums) {
        Stack<Integer> stack = new Stack<>();
    	for(int x:nums){
    		if(x!=0){
    			stack.push(x);
    		}
    	}
    	while(stack.size()<nums.length){
    		stack.push(0);
    	}
    	
    	for(int i = nums.length-1;i>=0;i--){
    		nums[i] = stack.pop();
    	}
    }
    

    }


  • 0

    Only beats 27% now.


Log in to reply
 

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