[Leetcode 2] 27 Remove Element

Problem:

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:

Use two pointers, ptrA points to the next-valid-to-copy place; ptrB go through the input array, if *ptrB equals the given value K, skip this position else copy it to *(++ptrA) position. Considering some special case: 1. A=[], K=anyValue, need to return 0; 2. A=[k, k, k] K=k, need to return 0;

The time complexity is O(n) and the space complexity is O(n)

 

Code:

public class Solution {
    public int removeElement(int[] A, int elem) {
        // Start typing your Java solution below
        // DO NOT write main() function
        //if (A.length == 0) return 0;
        
        int a=0;
        for (int b=0; b<A.length; b++) {
            if (A[b] != elem) {
                A[a++] = A[b];
            }
        }
        
        return a;
    }
}

 

Attention:

Since here A always point to the next-to-copy place, the special case A = [] can be merged into the general solution

posted on 2013-04-06 13:30  freeneng  阅读(163)  评论(0编辑  收藏  举报

导航