Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 664da4e

Browse files
committed
add 49, update 148
1 parent 8995d5b commit 664da4e

File tree

2 files changed

+56
-14
lines changed

2 files changed

+56
-14
lines changed

0049-group-anagrams.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
"""
2+
49. Group Anagrams
3+
4+
Submitted: February 11, 2025
5+
6+
Runtime: 21 ms (beats 24.46%)
7+
Memory: 20.82 MB (beats 56.56%)
8+
"""
9+
10+
class Solution:
11+
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
12+
strs.sort(key=sorted)
13+
return [list(group) for (key, group) in itertools.groupby(strs, key=sorted)]

0148-sort-list.cpp

Lines changed: 43 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
/*
22
148. Sort List
33
4-
Submitted: February 10, 2025
4+
Submitted: February 11, 2025
55
6-
Runtime: 7 ms (beats 96.37%)
7-
Memory: 58.09 MB (beats 75.27%)
6+
Runtime: 7 ms (beats 96.40%)
7+
Memory: 55.79 MB (beats 99.18%)
88
*/
99

1010
/**
@@ -17,14 +17,43 @@ Memory: 58.09 MB (beats 75.27%)
1717
* ListNode(int x, ListNode *next) : val(x), next(next) {}
1818
* };
1919
*/
20-
class Solution {
21-
public:
22-
ListNode* sortList(ListNode* head) {
23-
vector<int> v;
24-
for (ListNode* p = head; p != nullptr; p = p->next) v.push_back(p->val);
25-
sort(v.begin(), v.end());
26-
auto it = v.cbegin();
27-
for (ListNode* p = head; p != nullptr && it != v.cend(); p = p->next, ++it) p->val = *it;
28-
return head;
29-
}
30-
};
20+
21+
class Solution {
22+
public:
23+
ListNode* sortList(ListNode* head) {
24+
if (head == nullptr || head->next == nullptr) return head;
25+
int size = 0;
26+
for (ListNode* p = head; p != nullptr; p = p->next) ++size;
27+
if (size == 2) {
28+
if (head->val > head->next->val) swap(head->val, head->next->val);
29+
return head;
30+
}
31+
ListNode* beforeHalf = head;
32+
for (int i = 0; i < (size / 2) - 1; ++i) beforeHalf = beforeHalf->next;
33+
ListNode* half = beforeHalf->next;
34+
beforeHalf->next = nullptr;
35+
ListNode* newHead = mergeTwoLists(sortList(head), sortList(half));
36+
return newHead;
37+
}
38+
// from 21-merge-two-sorted-lists
39+
ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
40+
if (list1 == nullptr) return list2;
41+
if (list2 == nullptr) return list1;
42+
ListNode* head = list1->val > list2->val ? list2 : list1;
43+
if (head == list1) list1 = list1->next;
44+
else list2 = list2->next;
45+
ListNode* tail = head;
46+
while (list1 != nullptr && list2 != nullptr) {
47+
if (list1->val > list2->val) {
48+
tail->next = list2;
49+
list2 = list2->next;
50+
} else {
51+
tail->next = list1;
52+
list1 = list1->next;
53+
}
54+
tail = tail->next;
55+
}
56+
tail->next = list1 == nullptr ? list2 : list1;
57+
return head;
58+
}
59+
};

0 commit comments

Comments
 (0)