What could I do to fix this "move zeroes" issue?


  • -1
    A
           public class Solution {
        public void moveZeroes(int[] nums) {
            if (nums == null || nums.length == 0)
            return;
            int position = 0;
            for (int i = 0; i < nums.length; i++){
                if (nums[i] != 0)
                nums[position++] = nums[i];
            }
        }
    }
    

    Input: [0,1,0,3,12]

    My output: [1,3,12,3,12]

    Expected output: [1,3,12,0,0]

    What could I do to fix this?


  • 0
    V

    Rather than equating the value of nums[position++] to nums[i], try swapping them. Then the code will look like this:

    public class Solution {

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

    }


  • 0
    S
    class Solution(object):
        def moveZeroes(self, nums):
            """
            :type nums: List[int]
            :rtype: void Do not return anything, modify nums in-place instead.
            """
            return nums.sort(key=lambda x:x==0)

Log in to reply
 

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