本文共 821 字,大约阅读时间需要 2 分钟。
题目:
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.
思路:给定一个vector和一个整数,删除vector中与这个整数相等的所有数的位置,并返回新vector的大小
代码:
class Solution {public: int removeElement(vector & nums, int val) { vector ::iterator iter = nums.begin(); while (iter != nums.end()){ if (val == *iter){//当前位置的数如果和给定的val相等,则用erase()删除,并返回当前位置下一个位置的iterator赋给iter iter = nums.erase(iter); } else{//如果不相等,则iter递增 ++iter; } } return nums.size(); }};
转载地址:http://ynmii.baihongyu.com/