Remove Element Solutions in C++
Number 27
Difficulty Easy
Acceptance 48.3%
Link LeetCode
Other languages Go
Solutions
C++ solution by haoel/leetcode
// Source : https://oj.leetcode.com/problems/remove-element/// Author : Hao Chen// Date : 2014-06-19class Solution {public:int removeElement(vector<int>& nums, int val) {int pos = 0;for (int i=0; i<nums.size(); i++){if (nums[i] != val){nums[pos++] = nums[i];}}return pos;}int removeElement(int A[], int n, int elem) {int tail = n-1;int i = 0;while ( i<=tail ){if (A[i]==elem){A[i] = A[tail--];continue;}i++;}return tail+1;}};
C++ solution by pezy/LeetCode
#include <algorithm>class Solution {public:int removeElement(int A[], int n, int elem){for (int i = 0; i < n;){if (A[i] == elem) std::swap(A[i], A[--n]);else ++i;}return n;}};
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/remove-element//// Author : liuyubobobo/// Time : 2016-12-05#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 newl = 0;for( int i = 0 ; i < nums.size() ; i ++ )if( nums[i] != val )nums[newl++] = nums[i];return newl;}};int main() {vector<int> nums = {3, 2, 2, 3};int val = 3;cout << Solution().removeElement(nums, val) << endl;return 0;}
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/remove-element//// Author : liuyubobobo/// Time : 2016-12-05#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 newl = nums.size();int i = 0;while( i < newl )if( nums[i] == val )nums[i] = nums[--newl];elsei ++;return newl;}};int main() {vector<int> nums = {3, 2, 2, 3};int val = 3;cout << Solution().removeElement(nums, val) << endl;return 0;}