UpperBound BS
#include <bits/stdc++.h>
using namespace std;
int greaterElement(vector<int> v, int x){
//binary search wihtout equal check:
int l = 0;
int h = v.size()-1;
while(l <= h){
int m = s + (e-s)/2;
if(v[m] < x){
//approach to closer == value, ignore smaller values:
l = m+1;
}
else if(v[m] > x){
//compress the space:
h = m-1;
}
else if(v[m] == x){
//go closer to larger, ignore smaller(+equals):
//means increament in right direction:
l = m+1;
}
}
//after this no equal condition check, condition will arise: h mid l and sicne sorted we return l.
if(l < v.size()) return v[l];
else return v[0];
}
int main(){
//Q: You are given an array and a target value, you have to return the smallest element that is greater than the target with cycle.
int n;
cin >> n;
int target;
cin >> target;
vector<int> arr;
for(int i=0;i<n;i++){
int x;
cin >> x;
arr.push_back(x);
}
cout << greaterElement(arr, target) << endl;
return 0;
}
Comments
Post a Comment