Remove Element - leetcode

来源:互联网 发布:syslog centos 编辑:程序博客网 时间:2024/04/28 13:46

Remove Element

 My Submissions

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.


思路:利用依次覆盖的方法进行处理。

class Solution {public:    int removeElement(int A[], int n, int elem) {        // Note: The Solution object is instantiated only once and is reused by each test case.        if (n < 1)            return 0;        int k = 0;        for (int i = 0; i < n; ++i) {            if (A[i] != elem ) {                swap (A[i - k], A[i]);            }            else {                ++k;            }        }        return n - k;    }};



原创粉丝点击