🎀 The Problem
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.
Example:
Input: nums = [3,2,2,3], val = 3
Output: 2, nums = [2,2,,]
👩💻 My Answer
class Solution {
public int removeElement(int[] nums, int val) {
int i, j;
int k = 0;
Arrays.sort(nums);
for (i = 0; i < nums.length; i++) {
if (nums[i] == val) {
j = i + 1;
while (j < nums.length && nums[j] == val) {
j++;
}
if (j != nums.length) {
nums[i] = nums[j];
nums[j] = val;
k++;
}
} else
k++;
}
return k;
}
}
Good & Bad
- ✅ I did it on my own!
- ✖️ Runtime & Memory
💋 Ideal Answer
Approach - "Two Pointers"
Because I learned about Two Pointers from the last post, I want to use two pointers for this problem as well to improve the runtime & memory.
1: Initialize index to 0, which represents the current position for the next non-target element.
2: Iterate through each element of the input array using the i pointer.
3: For each element nums[i], check if it is equal to the target value.
If nums[i] is not equal to val, it means it is a non-target element.
Set nums[index] to nums[i] to store the non-target element at the current index position.
Increment index by 1 to move to the next position for the next non-target element.
4: Continue this process until all elements in the array have been processed.
5: Finally, return the value of index, which represents the length of the modified array.
I also watched the YouTube video to understand better.
Developer Docs's Remove Element Explanation
New Code
class Solution {
public int removeElement(int[] nums, int val) {
int index = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] != val) {
nums[index] = nums[i];
index++;
}
}
return index;
}
}
💡 What I Learned
- Do not use for and while loop multiple times if you want to improve efficiency.
Top comments (0)