mirror of
https://github.com/20kaushik02/leetcode-gulag.git
synced 2026-01-25 07:34:05 +00:00
day 23: 704-binary-search, 347-top-k-frequent-elements
This commit is contained in:
10
704-binary-search/driver.cpp
Normal file
10
704-binary-search/driver.cpp
Normal 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;
|
||||
}
|
||||
25
704-binary-search/soln.cpp
Normal file
25
704-binary-search/soln.cpp
Normal 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;
|
||||
}
|
||||
8
704-binary-search/soln.hpp
Normal file
8
704-binary-search/soln.hpp
Normal 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);
|
||||
};
|
||||
Reference in New Issue
Block a user