Easy to understand 3 lines Java solution

  • 0

    The idea is to use two pointers. One pointer (cur) is sweeping the array while the other one (s) points to the space to store the next non-zero element. At the beginning both point to num[0], then (cur) starts to sweep the array. Once the sweeping pointer (cur) encounters a non-zero element, this number will be copied to the element pointed by (s), and (s) increments to the next element for further incoming numbers. After (cur) iterates all elements of nums, all non-zero elements have been moved to the beginning of the array with the same order they were. We then set all elements after (s) to be 0.

    public class Solution {
        public void moveZeroes(int[] nums) {
            int cur=0,s=0;
            while(cur<nums.length) if (nums[cur++]!=0) nums[s++]=nums[cur-1];
            while(s<nums.length) nums[s++]=0;

Log in to reply

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