-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path26_RemoveDuplicatesfromSortedArray.cpp
More file actions
54 lines (53 loc) · 1.06 KB
/
Copy path26_RemoveDuplicatesfromSortedArray.cpp
File metadata and controls
54 lines (53 loc) · 1.06 KB
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
45
46
47
48
49
50
51
52
53
54
/*
Given a sorted array nums, remove the duplicates in-place
such that each element appear only once and return the new length.
Do not allocate extra space for another array,
you must do this by modifying the input array in-place with O(1) extra memory.
*/
#include<iostream>
#include<vector>
using namespace std;
int removeDuplicates(vector<int>& nums) {
int i = 1, j = 0;
if (nums.size() >= 2) {
while (i < nums.size()) {
if (nums[i] == nums[j]) {
i++;
}
else {
if (i - j != 1) {
nums[++j] = nums[i];
i++;
}
else {
i++;
j++;
}
}
}
j++;
}
else
j = nums.size();
return j;
}
int removeDuplicates_1(vector<int>& nums) {
int begin = 0, end = 1;
if (nums.size() < 2) return nums.size();
while (end < nums.size()) {
if (nums[begin] != nums[end]) {
begin++;
nums[begin] = nums[end];
}
else {
end++;
}
}
begin++;
return begin;
}
int main() {
vector<int> n = { 0,0,1,1,1,2,2,3,3,4 };
//cout << removeDuplicates(n);
cout << removeDuplicates_1(n);
}