Remove elements (Force Button No.27)
1. Brute force cracking of two-layer for loop, time complexity n^2
2. Double pointer method, time complexity n, using a fast pointer and a slow pointer to complete the work of two for loops in one for loop.
The double pointer method is very common in arrays and linked lists, and is used in many interview questions that examine arrays, linked lists, and strings.
int removeElement(vector<int>& nums, int val) { int slowIndex = 0; for (int fastIndex = 0; fastIndex < nums.size(); fastIndex++) { if (nums[fastIndex] ! = val) { nums[slowIndex++] = nums[fastIndex]; } } return slowIndex; }Copy the code