leetcode--Remove Element

来源:互联网 发布:大连pm2.5历年数据 编辑:程序博客网 时间:2024/06/11 01:47

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.

算法:

一:通过首尾双指针进行判断和交换,类似于快排。

二:访问一个元素,判断是不是elem,决定是不是要向前移动。

算法二实现如下:

java:

public class Solution {    public int removeElement(int[] A, int elem) {        int n = A.length;        if(n==0)            return 0;        int cnt=0;        for(int i=0;i<n;i++){            if(A[i]==elem){                cnt++;            }else{                A[i-cnt]=A[i];            }        }        return n-cnt;    }}
c++:

class Solution {public:    int removeElement(int A[], int n, int elem) {        if(n==0)            return 0;        int cnt=0;        for(int i=0;i<n;i++){            if(A[i]==elem){                cnt++;            }else{                A[i-cnt]=A[i];            }        }        return n-cnt;    }};






0 0
原创粉丝点击