Leetcode: Remove Element

Given an array and a value, remove all instances of that value in place and return the new length.

The order of elements can be changed. It doesn’t matter what you leave beyond the new length.

 

public int removeElement(int[] A, int elem) {
        // Start typing your Java solution below
        // DO NOT write main() function
        if(A==null||A.length==0){
            return 0;
        }
        int end = A.length-1;
        int index = 0;
        while(index<=end){
            if(A[index]==elem){
                swap(A, index, end);
                end--;
            }else{
                index++;
            }            
        }
        return end+1;
    }
    
    public void swap(int[] A, int i, int j){
        int tmp = A[i];
        A[i] = A[j];
        A[j] = tmp;
    }
FacebookTwitterGoogle+Share

Leave a Reply

Your email address will not be published. Required fields are marked *