c++ 笔试每日一题(leetcode 之 remove element)

描述:
        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
 

 

(1)现在考虑数组包含很少的要删除的元素的情况。例如,num=[1,2,3,5,4],Val=4。之前的算法会对前四个元素做不必要的复制操作。另一个例子是 num=[4,1,2,3,5],Val=4。似乎没有必要将 [1,2,3,5这几个元素左移一步

(2) val = 4

 while( i < j )

(3)如果nums[i] != val,

i ++;

(4)如果 nums[i] = val

则  nums[i] = nums[j]

然后j--;

(5)while( i < j )不成立,从而跳出循环

#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
using namespace std;
/**
 * @brief   remove  Element
 * @date:2020-1-14
 */
class Solution{
public:
    int RemoveElement(vector<int> &nums,int  val){
      int j=0;
      for(int i=0;i<nums.size();i++){
       if(nums[i]!=val)
          nums[j++]=nums[i];
      }
      return j;
    }

};
class soluton2{
public:
    int RemoveElement2(vector<int>& nums,int  val){
        int j=nums.size();
        int i=0;
        while(i<j){
           if(nums[i]==val)
               nums[i]=nums[--j];
           else
               ++i;
        }
        return j;
    }
};
void  display(const int & data)
{
    cout<<data<<' ';

}
int main(int argc, char *argv[])
{
    int a[]={1,0,-1,0,-2,2};
    vector<int> vec(a,a+sizeof(a)/sizeof(int));
    for_each(vec.begin(),vec.end(),display);
    cout<<endl;
    Solution s1;
    soluton2  s2;
   // int result=s1.RemoveElement(vec,1);
    int result2=s2.RemoveElement2(vec,1);
   // cout<<result<<endl;
    cout<<result2<<endl;

    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值