-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathremove duplicate from sorted array - explain
66 lines (42 loc) · 1.21 KB
/
remove duplicate from sorted array - explain
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
55
56
57
58
59
60
61
62
63
64
65
66
the array is sorted, we need to keep. track of unique elements and put them at first place.
example: [1,1,2,2] , output: [1,2]
return value should be the size of new array
we have two pointers: one to keep track of unique number and another one is to keep finding the different value in the array
two pointers: i and j
i=0, j=1 till the end of array
check if nums[i] == nums[j] :=> do j=j+1
else if nums[i]!=nums[j] :=> increment i by 1 and put nums[j] to nums[i]
for [1,1,2,2]
[0,1,2,3]
pass 1: i=0,j=1
1 == 1 --> j=2, i=0
pass 2: i=0,j=2
1 != 2 --> i=1, arr[1] = 2
[1,2,2,2]
pass 3: i=1, j=2
2 == 2 --> i=1, j=3
pass 4: i=1, j=3
2 == 2 --> i=1, j=4 == size of array
break out of loop
return i+1 i.e. 1+1 = 2
result array would be [1,2,2,2] trace to 2 length
Solution:
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
if(nums.size()<2){
return nums.size();
}
int i=0,j=1;
while(j!=nums.size()){
if(nums[i]!=nums[j]){
i++;
nums[i]=nums[j];
}
else{
j++;
}
}
return i+1;
}
};