【题目描述】
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.
【思路】水题一道,思路跟Remove Duplicates from Sorted Array类似。
【代码】
class Solution { public: int removeElement(vector<int>& nums, int val) { int n=nums.size(); if(n==0) return n; int ans=0; for(int i=0;i<n;i++){ if(nums[i]!=val){ nums[ans]=nums[i]; ans++; } } nums.resize(ans); return ans; } };
本文介绍了一种在数组中高效移除特定值的方法,并提供了一个C++实现示例。该算法通过一次遍历的方式将不等于指定值的元素重新排列到数组的前部,并返回新的有效长度。
668

被折叠的 条评论
为什么被折叠?



