class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int n=nums.size();
for(int i=0;i<n;i++) {
if(nums[i]==val){
int j=i;
while(j<n-1){
nums[j]=nums[j+1];
j++;
}
n--;
i--;
}
}
return n;
}
};
Time Complexity: O(n^2)
Space Complexity: O(1)
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int slowIndex = 0;
for (int fastIndex = 0; fastIndex < nums.size(); fastIndex++) {
if (val != nums[fastIndex]) {
nums[slowIndex++] = nums[fastIndex];
}
}
return slowIndex;
}
};
Time Complexity:O(n)
Space Complexity:O(1)
class Solution {
public int removeElement(int[] nums, int val) {
int slowIdx=0;
for(int fastIdx=0;fastIdx<=nums.length-1;fastIdx++){
if(nums[fastIdx]!=val){
nums[slowIdx++]=nums[fastIdx];
}
}
return slowIdx;
}
}