forked from Pr8862/pr_hacktoberfest-2k22
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path83. Remove Duplicates from Sorted List.cpp
65 lines (57 loc) · 1.69 KB
/
83. Remove Duplicates from Sorted List.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
//Runtime: 12 ms, faster than 100.00% of C++ online submissions for Remove Duplicates from Sorted List.
//Memory Usage: 9.2 MB, less than 65.42% of C++ online submissions for Remove Duplicates from Sorted List.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
if(head == NULL || head->next == NULL) return head;
ListNode* last = head;
ListNode* cur = head->next;
while(cur != NULL){
if(cur->val == last->val){
//remove cur
last->next = cur->next;
}else{
//update last only if cur isn't duplicate
last = cur;
}
cur = cur->next;
}
return head;
}
};
/**
Approach 1: Straight-Forward Approach
**/
/**
Time: O(n)
Space: O(1)
**/
//Runtime: 12 ms, faster than 100.00% of C++ online submissions for Remove Duplicates from Sorted List.
//Memory Usage: 9.2 MB, less than 55.04% of C++ online submissions for Remove Duplicates from Sorted List.
/**
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
if(head == NULL) return NULL;
ListNode* cur = head;
while(cur != NULL && cur->next != NULL){
if(cur->val == cur->next->val){
//remove cur->next
cur->next = cur->next->next;
//next time we compare cur and cur->next(which was cur->next->next)
}else{
cur = cur->next;
}
}
return head;
}
};
**/