-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathremove_duplicates_solution.cpp
More file actions
34 lines (25 loc) · 1.01 KB
/
remove_duplicates_solution.cpp
File metadata and controls
34 lines (25 loc) · 1.01 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
/*
Daniel Diaz
LeetCode Problem - Remove Duplicates from Sorted Array
- Description:
Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once.
The relative order of the elements should be kept the same.
*/
// - My Solution:
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
//if array of size 1, there are no duplicates -> just return 1
if (nums.size() == 1 ) return 1;
int currIndex = 0, count = 1;
//starting at the second element, we iterate until we reach a value greater than value at currIndex
for (int i = 1; i < nums.size(); ++i) {
if (nums[i] > nums[currIndex]) {
//set the next index of currIndex to current value and increment both count and currIndex
nums[++currIndex] = nums[i];
++count;
}
}
return count;
}
};