[LeetCode] Remove Element

27. Remove Element

Given an integer array nums and an integer val, remove all occurrences of val in nums 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:

1
2
3
4
5
6
7
8
9
10
11
12
>int[] nums = [...]; // Input array
>int val = ...; // Value to remove
>int[] expectedNums = [...]; // The expected answer with correct length.
// It is sorted with no values equaling val.

>int k = removeElement(nums, val); // Calls your implementation

>assert k == expectedNums.length;
>sort(nums, 0, k); // Sort the first k elements of nums
>for (int i = 0; i < actualLength; i++) {
assert nums[i] == expectedNums[i];
>}

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

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int res = 0;
for(int i = 0; i < nums.size(); i++) {
if(nums[i] == val) continue;
nums[res++] = nums[i];
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/07/30/PS/LeetCode/remove-element/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.