avatar

superorange0707

  • Homepage
  • Tag
  • Category
Home 283 - Move Zero
ๆ–‡็ซ 

283 - Move Zero

Posted 20 days ago
5~6 min read

[283 - Move Zero]

๐Ÿ”— LeetCode Link


Problem Description

Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements.
Note that you must do this in-place without making a copy of the array.


Idea

use two pointer so we only need to iterate once


Logic

  1. set slow pointer to mark current index
  2. set fast pointer and use it for iterating
  3. use fast pointer to find non-zero element
  4. swap the value between slow

Code (Java - Closed Interval)

class Solution {
    public void moveZeroes(int[] nums) {

        // set slow pointer
        int slow = 0;
        
        // use fast pointer in the loop
        for(int fast = 0; fast <= nums.length - 1; fast++){

            // exchange value when fast pointer point to non-zero element
            if(nums[fast] != 0){
                int tmp = nums[slow];

                // move slow pointer
                nums[slow++] = nums[fast];
                nums[fast] = tmp;
            }
        }
    }
}
two pointer
Leetcode Array two pointer
Share

Further Reading

Apr 23, 2025

283 - Move Zero

[283 - Move Zero] ๐Ÿ”— LeetCode Link Problem Description Given an integer array nums, move all 0's to the end of it while maintaining the relative order

Apr 23, 2025

27 - Remove Element

[27 - Remove Element] ๐Ÿ”— LeetCode Link Problem Description Given an integer array nums and an integer val, remove all occurrences of val in nums in-pl

Apr 23, 2025

26 - Remove Duplicates from Sorted Array

[26 - Remove Duplicates from Sorted Array] ๐Ÿ”— LeetCode Link Problem Description Given an integer array nums sorted in non-decreasing order, remove the

OLDER

27 - Remove Element

NEWER

Migrating Jenkins SCM Using GitLab from Bitbucket: SCM URL Bulk Replacement

Recently Updated

  • Migrating Jenkins SCM Using GitLab from Bitbucket: SCM URL Bulk Replacement
  • 283 - Move Zero
  • 27 - Remove Element
  • 26 - Remove Duplicates from Sorted Array
  • Migrating from Bitbucket to GitLab? Hereโ€™s how to keep your teams moving without missing a beat!

Trending Tags

Course two pointer Binary Tree Hash SQL Leetcode Error Recording Gitlab Bitbucket Devops

Contents