本文共 1749 字,大约阅读时间需要 5 分钟。
Given an array and a value, remove all instances of that value in place and return the new length.
Do not allocate extra space for another array, you must do this in place with constant memory.
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
Example:
Given input array nums = [3,2,2,3]
, val = 3
Your function should return length = 2, with the first two elements of nums being 2.
本题如上面所说的,你要返回一个数组和一个长度(答案检查中不管这个长度之后的元素),因而只需要使得到的数组在返回回来的长度内没有包含规定的数组就可以了。class Solution {public: int removeElement(vector & nums, int val) { int len(nums.size()); if(0 == len) return 0; //方法1 开销大 重新分配 for(int i=0; i
class Solution {public: int removeElement(vector & nums, int val) { int len(nums.size()); if(0 == len) return 0; //方法1 int count(0); auto it = nums.begin(); for(int i=0; i
class Solution {public: int removeElement(vector & nums, int val) { int len(nums.size()); if(0 == len) return 0; //方法3 int pos(0); while(true) { auto it = nums.begin(); if(nums[pos] == val) { nums.erase(it+pos); if(0 == nums.size()) break; pos = 0; continue; } ++pos; if(pos >= nums.size()) break; } return static_cast (nums.size()); }};