pranay_teja
11/17/2018 - 8:41 AM

LeetCode-RemoveElement

#include<bits/stdc++.h>
using namespace std;

int removeElement(vector<int>& a, int val) {
    // removes the element with value 'val'
    // and returns the new length of array
    // Space complexity should be O(1)
    // No extra array allowed
    int counter=0;
    for(int i=0;i<a.size();i++){
        if(a[i]!=val){
            a[counter]=a[i];
            counter++;
        }
    }
    return counter;
}

int main(){
    // freopen("ip.txt","r",stdin);
    int t;
    cin>>t;
    while(t--){
        int n;
        cin>>n;
        vector<int> a(n);
        for(int i=0;i<n;i++){
            cin>>a[i];
        }
        int val;
        cin>>val;
        int newLength=removeElement(a,val);
        for(int i=0;i<newLength;i++){
            cout<<a[i]<<" ";
        }
        cout<<endl;
    }
    return 0;
}