27. Remove Element
问题:
删除数组中的元素val。
返回剩下数组的size。
Example 1: Input: nums = [3,2,2,3], val = 3 Output: 2, nums = [2,2] Explanation: Your function should return length = 2, with the first two elements of nums being 2. It doesn't matter what you leave beyond the returned length. For example if you return 2 with nums = [2,2,3,3] or nums = [2,2,0,0], your answer will be accepted. Example 2: Input: nums = [0,1,2,2,3,0,4,2], val = 2 Output: 5, nums = [0,1,4,0,3] Explanation: Your function should return length = 5, with the first five elements of nums containing 0, 1, 3, 0, and 4. Note that the order of those five elements can be arbitrary. It doesn't matter what values are set beyond the returned length. Constraints: 0 <= nums.length <= 100 0 <= nums[i] <= 50 0 <= val <= 100
解法:slow-fast pointers(快慢指针)
- 0~slow-1:满足题意的数组。
- fast:探测是否存在非val的值。
- 如果 是非val:将fast指向的值加入前面满足题意的数组中,将不满足的slow放到后面。
- swap(slow, fast)
- slow++
- 继续下一个探测fast++
代码参考:
1 class Solution { 2 public: 3 int removeElement(vector<int>& nums, int val) { 4 int n=nums.size(); 5 int i=0, j=0; 6 if(n==0) return 0; 7 while(j<n) { 8 if(nums[j]!=val) { 9 swap(nums[i], nums[j]); 10 i++; 11 } 12 j++; 13 } 14 return i; 15 } 16 };