5/30/2014

18. Remove Element

public class Solution {
    public int removeElement(int[] A, int elem) {
        if (A.length==0) return 0;
        if (A.length==1 && A[0]==elem) return 0;
        if (A.length==1 && A[0]!=elem) return 1;
     
        int p = 0;
        int q = A.length - 1;
     
        while (p<q) {
            if (A[p]!=elem) {
                p++;
                continue;
            }
         
            if (A[q]==elem) {
                q--;
                continue;
            }
         
            int temp = A[q];
            A[q] = A[p];
            A[p] = temp;
        }
     
        if (A[p]==elem) return p;
        else return p+1;
    }
}

没有评论:

发表评论