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
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.
Solution :
[
class Solution {
public int removeElement(int[] nums, int val) {
int counter = 0;
for (int i = 0; i < nums.length; i++){
if (nums[i] != val){
nums[counter] = nums[i];
counter++;
}
}
return counter;
}
}
]
Explanation :
All you have to do is take elements not equal to K and put them before the k elements in an array. So we make a counter start at 0.
Now we run a for loop over the given array. Whenever you find an element that is not equal to k you put that element into the position of the array[counter].
All the elements which are not equal to k will be at the start of the array. Now return counter.
Time Complexity : O (N)
Space Complexity : O (1)
Let me know in the comments what you think about this problem.
COMMENTS