fork download
  1. #include <iostream>
  2. #include <bits/stdc++.h>
  3. using namespace std;
  4.  
  5. int findIndex(vector<int>nums,int target){
  6. int n=nums.size();
  7. int ans=-1;
  8. int low=0;
  9. int high=n-1;
  10.  
  11. while(low<=high){
  12. int mid=(low+high)/2;
  13. if(nums[mid]>target){
  14. ans=nums[mid];
  15. high=mid-1;
  16. }
  17. else{
  18. low=mid+1;
  19. }
  20. }
  21. return ans;
  22. }
  23. int main(){
  24. int n;
  25. cin>>n;
  26. vector<int>nums(n);
  27. for(int i=0;i<n;i++){
  28. cin>>nums[i];
  29. }
  30. int target;
  31. cin>>target;
  32. int index=findIndex(nums,target);
  33. cout<<"The smallest element greater than given target: "<<index<<endl;
  34. return 0;
  35. }
Success #stdin #stdout 0.01s 5316KB
stdin
5
1 2 3 4 5
3
stdout
The smallest element greater than given target: 4