classSolution{public:intremoveElement(vector<int>& nums,int val){int n = nums.size();int left =0;for(int right =0; right < n; right++){if(nums[right]!= val){
nums[left]= nums[right];
left++;}}return left;}};
方法二:
classSolution{public:intremoveElement(vector<int>& nums,int val){int left =0, right = nums.size();// 首尾指针进行收缩,首指针的元素与val进行比较并更新。while(left < right){if(nums[left]== val){
nums[left]= nums[right -1];
right--;}else{
left++;}}return left;}};