My O(n) solution


  • 7
    A
    class Solution {
    public:
        int removeElement(int A[], int n, int elem) {
            int index = 0;
            int tail = n - 1;
            
            while(index <= tail){
                if(A[index] == elem){
                    A[index] = A[tail];
                    tail -= 1;
                }else{
                    index++;
                }     
            }
            
            return tail + 1;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.