forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main2.cpp
44 lines (33 loc) · 853 Bytes
/
main2.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/// 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];
else
i ++;
return newl;
}
};
int main() {
vector<int> nums = {3, 2, 2, 3};
int val = 3;
cout << Solution().removeElement(nums, val) << endl;
return 0;
}