
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Coincidence Search in C++
Suppose we have a list of unique integers called nums. We have to find the number of integers that could still be successfully found using a standard binary search.
So, if the input is like [2,6,4,3,10], then the output will be 3, as if we use binary search to look for 4, we can find it at first iteration. We can also find 2 and 10 after two iterations.
To solve this, we will follow these steps −
Define a function help(), this will take target, an array & nums,
low := 0
high := size of nums - 1
while low <= high, do −
mid := low + (high - low) / 2
if nums[mid] is same as target, then −
return true
if nums[mid] < target, then −
low := mid + 1
Otherwise
high := mid - 1
return false
From the main method, do the following −
ret := 0
for each element i in nums
ret := ret + help(i, nums)
return ret
Let us see the following implementation to get better understanding −
Example
#include <bits/stdc++.h> using namespace std; class Solution { public: bool help(int target, vector<int> & nums) { int low = 0; int high = nums.size() - 1; while (low <= high) { int mid = low + (high - low) / 2; if (nums[mid] == target) return true; if (nums[mid] < target) { low = mid + 1; } else { high = mid - 1; } } return false; } int solve(vector<int> & nums) { int ret = 0; for (int i : nums) { ret += help(i, nums); } return ret; } }; main() { Solution ob; vector<int> v = {2,6,4,3,10}; cout << (ob.solve(v)); }
Input
{2,6,4,3,10}
Output
3
- Related Articles
- What is meant by coincidence ?
- Binary search in C#
- Binary Search in C++
- Binary Search Tree - Search and Insertion Operations in C++
- Binary Search in C++ program?
- Search Suggestions System in C++
- Search Insert Position in C++
- Binary Search functions in C++ STL
- Search a 2D Matrix in C++
- Binary Search Tree Iterator in C++
- Unique Binary Search Trees in C++
- Binary Search a String in C++
- Explain Binary search in C language
- Recover Binary Search Tree in C++
- C++ Program to Search for an Element in a Binary Search Tree
