Thursday, February 6, 2014

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.

Solution:

public class Solution {
    public int removeElement(int[] A, int elem) {
        int length = A.length;
        for(int pos = A.length-1; pos>=0; pos--)
        {
            if(A[pos]== elem)
            exchange(A, pos, --length);
        }
        return length;
    }
    
    
    private void exchange(int[] A, int pos1, int pos2)
    {
        int temp = A[pos1];
        A[pos1] = A[pos2];
        A[pos2] = temp;
    }
}

No comments :

Post a Comment