[LeetCode27]Remove Element

来源:互联网 发布:数据集中存储的好处 编辑:程序博客网 时间:2024/05/29 11:22

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;    }




0 0
原创粉丝点击