leetcode--Remove Element

1.题目描述

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.

2.解法分析

这个题目稍微还有点意思,想出来解法之后感觉还比较巧妙。

class Solution {
public:
    int removeElement(int A[], int n, int elem) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        //核心思想是设置一个尾指针,一个遍历指针,遍历指针一旦遇到elem,立马从当前尾部找第一个不是elem的
        //元素互换
        int tail=n-1;
        int newLen=0;
        for(int i=0;i<n;++i)
        {
            if(i>tail)break;
            if(A[i]==elem)
            {
                while(A[tail]==elem)
                {
                    tail--;
                }
                
                if(tail<i)return newLen;
                A[i]=A[tail];
                newLen++;
                tail--;
            }
            
            else newLen++;
        }
        
        return newLen;
    }
};
原文地址:https://www.cnblogs.com/obama/p/3276681.html