Remove Element(删除数组某一元素)

来源:互联网 发布:法国劳动法改革 知乎 编辑:程序博客网 时间:2024/05/17 06:48
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(vector<int>& nums, int val) {        vector<int>a;        for(int i=0;i<nums.size();i++)        {            if(nums[i]!=val)            a.push_back(nums[i]);        }        nums=a;        return a.size();    }};别人的答案:int rm(vector<int> &arr, int value)  {      int cnt=0;      for(int i=0; i<arr.size(); i++)      {          if(arr[i]==value) cnt++;          else if (cnt>0)          {              arr[i-cnt] = arr[i];          }      }      return size-cnt;  }  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 == 0 ) return 0;        int len = n;        for (int i = 0, pos = 0; i < n; ++i)        {            if (A[i] == elem)                --len;            else                A[pos++] = A[i];        }        return len;    }};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 == 0 ) return 0;        int len = n;        for (int i = 0, pos = 0; i < n; ++i)        {            if (A[i] == elem)                --len;            else                A[pos++] = A[i];        }        return len;    }};
0 0
原创粉丝点击