27. Remove Element

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.

Custom Judge:

The judge will test your solution with the following code:

If all assertions pass, then your solution will be accepted.
 

Example 1:

Example 2:

Constraints:

  • 0 <= nums.length <= 100
  • 0 <= nums[i] <= 50
  • 0 <= val <= 100

From: LeetCode
Link: 27. Remove Element


Solution:

Ideas:
This function takes as input a pointer to an array of integers (nums), the size of the array (numsSize), and the integer value to be removed (val). The function iterates over the array and checks each element against val. If the current element does not match val, it is moved to the beginning of the array, effectively overwriting elements that do match val. The position of the last moved element (i) is returned, which equals the new size of the array after removal of val.
Code:
int removeElement(int* nums, int numsSize, int val){
    int i = 0;
    for (int j = 0; j < numsSize; j++) {
        if (nums[j] != val) {
            nums[i] = nums[j];
            i++;
        }
    }
    return i;
}
07-06 20:25