avatar

superorange0707

  • Homepage
  • Tag
  • Category
Home 27 - Remove Element
ๆ–‡็ซ 

27 - Remove Element

Posted 20 days ago
5~7 min read

[27 - Remove Element]

๐Ÿ”— LeetCode Link


Problem Description

Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The order of the elements may be changed. Then return the number of elements in nums which are not equal to val.
Consider the number of elements in nums which are not equal to val be k, to get accepted, you need to do the following things:
Change the array nums such that the first k elements of nums contain the elements which are not equal to val. The remaining elements of nums are not important as well as the size of nums.
Return k.


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-target element
  4. set the slow pointer = faster pointer then move the slow pointer

Code (Java - Closed Interval)

class Solution {
    public int removeElement(int[] nums, int val) {

        // set the slow pointer
        int slow = 0;

        // set  the faster pointer
        for(int fast = 0; fast <= nums.length -1;fast++){
            // we use the fast pointer to check values, and make sure the fist slow number elements are not equal to val
            if(nums[fast] != val){
                nums[slow++] = nums[fast];
            }
        }
        return slow;
    }
}
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

26 - Remove Duplicates from Sorted Array

NEWER

283 - Move Zero

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