diff --git a/contains-duplicate/dylan-jung.cpp b/contains-duplicate/dylan-jung.cpp new file mode 100644 index 0000000000..0030be096c --- /dev/null +++ b/contains-duplicate/dylan-jung.cpp @@ -0,0 +1,13 @@ +// TC: O(N), SC: O(N) + +class Solution { +public: + bool containsDuplicate(vector& nums) { + unordered_set s; + for(auto item: nums) { + if(s.count(item) > 0) return true; + s.insert(item); + } + return false; + } +}; diff --git a/house-robber/dylan-jung.cpp b/house-robber/dylan-jung.cpp new file mode 100644 index 0000000000..071fd50c0f --- /dev/null +++ b/house-robber/dylan-jung.cpp @@ -0,0 +1,18 @@ +// TC: O(N), SC: O(1) +class Solution { +public: + int rob(vector& nums) { + if (nums.size() == 1) return nums[0]; + + int prev2 = nums[0]; // dp[i-2] + int prev1 = max(nums[0], nums[1]); // dp[i-1] + + for (int i = 2; i < nums.size(); i++) { + int cur = max(prev1, prev2 + nums[i]); + prev2 = prev1; + prev1 = cur; + } + + return prev1; + } +}; diff --git a/longest-consecutive-sequence/dylan-jung.cpp b/longest-consecutive-sequence/dylan-jung.cpp new file mode 100644 index 0000000000..9e366735c7 --- /dev/null +++ b/longest-consecutive-sequence/dylan-jung.cpp @@ -0,0 +1,24 @@ +// TC: O(N), SC: O(N) + +class Solution { +public: + int longestConsecutive(vector& nums) { + auto s = unordered_set(); + for(int it : nums) { + s.insert(it); + } + + int m = 0; + for(int it : s) { + if(s.count(it-1) > 0) continue; + + int cnt = 0; + while(s.count(it+cnt) > 0){ + cnt++; + } + m = max(m, cnt); + } + + return m; + } +}; diff --git a/top-k-frequent-elements/dylan-jung.cpp b/top-k-frequent-elements/dylan-jung.cpp new file mode 100644 index 0000000000..4c0b62ec7b --- /dev/null +++ b/top-k-frequent-elements/dylan-jung.cpp @@ -0,0 +1,31 @@ +// TC: O(N), SC: O(N) +class Solution { +public: + vector topKFrequent(vector& nums, int k) { + unordered_map freq; + freq.reserve(nums.size() * 2); + for (int x : nums) { + ++freq[x]; + } + + int n = nums.size(); + vector> bucket(n + 1); + for (auto& p : freq) { + int num = p.first; + int cnt = p.second; + bucket[cnt].push_back(num); + } + + vector ans; + ans.reserve(k); + + for (int count = n; count >= 1 && ans.size() < k; --count) { + for (int num : bucket[count]) { + ans.push_back(num); + if (ans.size() == k) break; + } + } + + return ans; + } +}; diff --git a/two-sum/dylan-jung.cpp b/two-sum/dylan-jung.cpp new file mode 100644 index 0000000000..e1a723947b --- /dev/null +++ b/two-sum/dylan-jung.cpp @@ -0,0 +1,17 @@ +// TC: O(N), SC: O(N) + +class Solution { +public: + vector twoSum(vector& nums, int target) { + unordered_map m; + for(int i = 0; i < nums.size(); i++) { + m[nums[i]] = i; + } + for(int first = 0; first < nums.size(); first++) { + if(m.count(target - nums[first]) > 0 && first != m[target - nums[first]]) { + return {first, m[target - nums[first]]}; + } + } + return {}; + } +};