Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- int main()
- {
- ios_base::sync_with_stdio(0); cin.tie(0);
- int n=4;
- int arr[] = {0,0,1,2,3,3,4,4,9};
- int arrsize = sizeof(arr)/sizeof(arr[0]);
- //binary search the leftmost position that contains n
- //L = minimum, R = maximum, ans = to store ans once it's found, then continue searching for left-er answers
- int L=0,R=arrsize,m,ans;
- while(L<=R){
- m=(L+R)/2;
- //if m is answer or larger: search leftside
- if(arr[m]>=n){
- ans=m;
- R=m-1;
- }
- //if m is smaller: search rightside
- else L=m+1;
- }
- cout<<"The leftmost position that contains " << n << ": " << ans+1 << '\n';
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement