1 2 3 4 5 6 7 8 9 10
| class Solution { public: int removeElement(vector<int>& nums, int val) { int pt = 0; for(auto& num : nums) if(num != val) nums[pt++] = num; return pt; } };
|
最坏情况下,pt也需要同时遍历一遍nums
考虑到题目中说元素的顺序可以改变,所以针对这一个条件进行优化
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| class Solution { public: int removeElement(vector<int>& nums, int val) { int left = 0, right = nums.size(); while(left < right) { if(nums[left] == val) nums[left] = nums[right-- - 1]; else ++left; } return left; } };
|
review
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| class Solution { public: int removeElement(vector<int>& nums, int val) { if(nums.empty()) return 0; int n = nums.size(); int i = 0, j = n - 1; while(i <= j) { while(i <= j && nums[i] == val) swap(nums[i], nums[j--]); ++i; } return j + 1; } };
|