day 23: 704-binary-search, 347-top-k-frequent-elements

This commit is contained in:
Kaushik Narayan R 2023-10-22 13:30:38 -07:00
parent 8324410cbe
commit edf7da5e9f
6 changed files with 94 additions and 0 deletions

View File

@ -0,0 +1,10 @@
#include "soln.hpp"
int main()
{
vector<int> nums{1, 1, 1, 2, 2, 3}, answer{1, 2};
int k = 2;
Solution soln;
cout << "Found top frequent elements correctly? " << soln.test(nums, k, answer) << endl;
return 0;
}

View File

@ -0,0 +1,33 @@
#include "soln.hpp"
vector<int> Solution::topKFrequent(vector<int> &nums, int k)
{
// first get counts
unordered_map<int, int> counts;
for (int num : nums)
{
counts[num]++;
}
// make a vector indexed by counts. nums can have max nums.size() unique elements, +1 for 0
vector<vector<int>> counts_indexed(nums.size() + 1);
for (auto count : counts)
counts_indexed[count.second].push_back(count.first);
// iterate in reverse order to get most frequent elements
vector<int> result;
for (int i = counts_indexed.size() - 1; i > 0; i--)
{
for (int j = 0; j < counts_indexed[i].size(); j++)
{
result.push_back(counts_indexed[i][j]);
if (result.size() == k)
return result;
}
}
return result;
}
bool Solution::test(vector<int> &nums, int k, vector<int> &answer)
{
return topKFrequent(nums, k) == answer;
}

View File

@ -0,0 +1,8 @@
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
vector<int> topKFrequent(vector<int> &nums, int k);
bool test(vector<int> &nums, int k, vector<int> &answer);
};

View File

@ -0,0 +1,10 @@
#include "soln.hpp"
int main()
{
vector<int> nums{-1, 0, 3, 5, 9, 12};
int target = 9, answer = 4;
Solution soln;
cout << "Binary search done correctly ? " << soln.test(nums, target, answer) << endl;
return 0;
}

View File

@ -0,0 +1,25 @@
#include "soln.hpp"
int Solution::search(vector<int> &nums, int target)
{
int low = 0, high = nums.size() - 1;
int mid;
while (low != high)
{
mid = (low + high) / 2;
if (nums[mid] == target)
return mid;
else if (nums[mid] < target)
low = mid + 1;
else
high = mid;
}
if (nums[low] == target)
return low;
return -1;
}
bool Solution::test(vector<int> &nums, int target, int answer)
{
return search(nums, target) == answer;
}

View File

@ -0,0 +1,8 @@
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int search(vector<int> &nums, int target);
bool test(vector<int> &nums, int target, int answer);
};