Skip to content

Commit

Permalink
week 1
Browse files Browse the repository at this point in the history
  • Loading branch information
lhj8 committed Oct 1, 2024
1 parent c5ac395 commit d20b062
Show file tree
Hide file tree
Showing 3 changed files with 71 additions and 9 deletions.
22 changes: 19 additions & 3 deletions hj/week 1/AnagramGroups.cpp
Original file line number Diff line number Diff line change
@@ -1,3 +1,19 @@
//
// Created by hj on 9/30/24.
//
class Solution {
public:
vector<vector<string>> groupAnagrams(vector<string>& strs) {
vector<vector<string>> output;
unordered_map<string, vector<string>> um;

for (string &str : strs) {
string key = str;
sort(key.begin(), key.end());
um[key].push_back(str);
}

for (auto &val : um) {
output.push_back(val.second);
}

return output;
}
};
31 changes: 28 additions & 3 deletions hj/week 1/StringEncodeAndDecode .cpp
Original file line number Diff line number Diff line change
@@ -1,3 +1,28 @@
//
// Created by hj on 9/30/24.
//
class Solution {
public:

string encode(vector<string>& strs) {
string encoded = "";
for (auto &str : strs) {
encoded += to_string(str.size()) + "#" + str;
}
return encoded;
}

vector<string> decode(string s) {
vector<string> decoded;
int i = 0;

while (i < s.size()) {
int j = s.find('#', i);
int len = stoi(s.substr(i, j - i));

i = j + 1;
decoded.push_back(s.substr(i, len));

i += len;
}

return decoded;
}
};
27 changes: 24 additions & 3 deletions hj/week 1/TopKElementsInList .cpp
Original file line number Diff line number Diff line change
@@ -1,3 +1,24 @@
//
// Created by hj on 9/30/24.
//
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
unordered_map<int, int> um;
priority_queue<pair<int, int>> pq;
vector<int> output;

for (auto &num : nums) {
um[num]++;
}

for (auto &pair : um) {
pq.push({pair.second, pair.first});
}

while (k > 0) {
output.push_back(pq.top().second);
pq.pop();
k--;
}

return output;
}
};

0 comments on commit d20b062

Please sign in to comment.