[LeetCode27]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.

Analysis:

two pointers scan, one variable record the frequency of the value, detailed see in code

Java

public int removeElement(int[] A, int elem) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        int count = 0;
        for(int i=0;i<A.length;i++){
        	if(A[i] == elem)
        		count++;
        	else if(count>0)
        		A[i-count] = A[i];
        }
		return A.length - count;
    }

Another one:

public int removeElement(int[] A, int elem) {
        int count = 0;
        for(int i=0;i<A.length;i++){
        	if(A[i]!=elem){
        		A[count++]=A[i];
        	}else{
        		continue;
        	}
        }
        return count;
    }


c++

int removeElement(int A[], int n, int elem) {
        int cur =0;
    for(int i=0;i<n;i++){
        if(A[i]==elem)
            continue;
        A[cur] = A[i];
        cur++;
    }
    return cur;
    }




你可能感兴趣的:(LeetCode,array,数组)