问题描述:
一、第一种解题方法
(1)使用双指针发
val = 3;
(2)若nums[i] = val
i++,
(3)如果 nums[i] != val
则 nums[ j ] = nums[ i ]
然后 j++ ;
(4)完整的实现代码
#include <iostream>
#include <vector>
#include <cassert>
#include <stdexcept>
using namespace std;
/// Two Pointers
///Time Complexity: O(n)
/// Space Complexity: O(1)
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int j = 0;
for( int i = 0 ; i < nums.size() ; i ++ )
if( nums[i] != val )
nums[j++] = nums[i];
return j;
}
};
int main() {
vector<int> nums = {3, 2, 2, 3};
int val = 3;
cout << Solution().removeElement(nums, val) << endl;
return 0;
}
二、第二中解题方法
(1)现在考虑数组包含很少的要删除的元素的情况。例如,num=[1,2,3,5,4],Val=4num=[1,2,3,5,4],Val=4。之前的算法会对前四个元素做不必要的复制操作。另一个例子是 num=[4,1,2,3,5],Val=4num=[4,1,2,3,5],Val=4。似乎没有必要将 [1,2,3,5][1,2,3,5] 这几个元素左移一步
(2) val = 4
while( i < j )
(3)如果nums[i] != val,
i ++;
(4)如果 nums[i] = val
则 nums[i] = nums[j]
然后j--;
(5)while( i < j )不成立,从而跳出循环
(6)代码的完整实现:
#include <iostream>
#include <vector>
#include <cassert>
#include <stdexcept>
using namespace std;
/// Two Pointers
/// Move the deleted element to the last
/// This method would be save the unnecessary copy when the removed element is rare.
///
/// Time Complexity: O(n)
/// Space Complexity: O(1)
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int j = nums.size();
int i = 0;
while( i < j )
if( nums[i] == val )
nums[i] = nums[--j];
else
i ++;
return j;
}
};
int main() {
vector<int> nums = {1, 2, 3,5,4};
int val = 4;
cout << Solution().removeElement(nums, val) << endl;
return 0;
}
参考资料: