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的所有项,分别与val比较
#include <iostream> #include <vector> using namespace std;
/* 思路:遍历vector的所有项,分别与val比较 相同: index不加,nums[i] 赋值给nums[index] 不相同:index加1,不需要赋值 时间复杂度O(n),空间复杂度O(1) */ class Solution { public: int removeElement(vector<int>& nums, int val) { int index = 0; for (size_t i = 0; i < nums.size(); ++i) { if (nums[i] != val) nums[index++] = nums[i]; } return index; } };
int main() { using namespace std; Solution sol; vector<int> vec{1, 2, 5, 6, 12, 45, 8, 4, 5, 4}; cout << "Original vector's size is " << vec.size() << endl; int count = sol.removeElement(vec, 5); cout << "New vector's size is " << count << endl; for (int i = 0; i < count; ++i) cout << "vec[" << i << "] = " << vec[i] << endl; return 0; }
思路:利用remove和distance函数实现。 参考来自于:https://github.com/soulmachine/leetcode remove MSDN介绍 remove 博客参考 distance MSDN介绍
template<class ForwardIterator, class T> ForwardIterator remove(ForwardIterator first, ForwardIterator last, const T& value);
一个指向最后一个的下一个“不删除的”元素的迭代器。返回值是区间的“新逻辑终点”。
vector中的remove的作用是将等于value的元素放到vector的尾部,但并不减少vector的size
template<class InputIterator> typename iterator_traits<InputIterator>::difference_type distance( InputIterator _First, InputIterator _Last );
_First和_Last之间元素的个数。
Header: <iterator> Namespace: std
#include <iostream> #include <algorithm> #include <vector> using namespace std;
/* 思路:利用distance和remove函数实现 时间复杂度O(n),空间复杂度O(1) */ class Solution2 { public: int removeElement(vector<int>& nums, int val) { return distance(nums.begin(), remove(nums.begin(), nums.end(), val)); } };
vector<int> vec2{3,2,2,3}; int count = sol2.removeElement(vec2, 3); cout << "New vector2's size is " << count << endl; cout << "New vector2's real size is " << vec2.size(); for (int i = 0; i < count; ++i) cout << "vec[" << i << "] = " << vec2[i] << endl;
完整代码见于GitHub 。