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

This commit is contained in:
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, 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);
};