Simple Java solution


  • 0
    S

    Use same way as remove element

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

Log in to reply
 

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