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) {
         for(int i = 0; i < n; i++){  
            if(A[i] == elem){  
                swap(A[i],A[n-1]);  
                --n;  
                --i;  
            }  
        }  
        return n;  
    }
};

思路:题目的意思比較简单就是数组中删除一些元素,跟输入的值一样,然后返回数组长度。普通情况下数组中删除一个元素,后面的所有元素都要往前面移,非常慢的。但题目中说,数组内的内容能够任意更改。所以能够用一种比較快的方式删除,就是不删除,直接与最后一个元素交换,然后缩小数组长度。

http://www.waitingfy.com/archives/1632

原文地址:https://www.cnblogs.com/hrhguanli/p/4514537.html