fork download
  1. import java.util.*;
  2. import java.lang.*;
  3. import java.io.*;
  4.  
  5. /* Name of the class has to be "Main" only if the class is public. */
  6. class Ideone
  7. {
  8. public static void main (String[] args) throws java.lang.Exception
  9. {
  10. // your code goes here
  11. int[] arr={1,2,2,7,8,8,8,8,9,10};
  12. int k=8;
  13. System.out.print(first(arr,k)+" "+last(arr,k));
  14. }
  15. public static int first(int[] arr,int k){
  16. int i=0;
  17. int j=arr.length-1;
  18. int ans=-1;
  19. while(i<=j){
  20. int mid=(i+j)/2;
  21. if(arr[mid]==k){
  22. ans=mid;
  23. j=mid-1;
  24. }
  25. else if(arr[mid]>k){
  26. j=mid-1;
  27. }
  28. else{
  29. i=mid+1;
  30. }
  31. }
  32. return ans;
  33.  
  34. }
  35.  
  36. public static int last(int[] arr,int k){
  37. int i=0;
  38. int j=arr.length-1;
  39. int ans=-1;
  40. while(i<=j){
  41. int mid=(i+j)/2;
  42. if(arr[mid]==k){
  43. ans=mid;
  44. i=mid+1;
  45. }
  46. else if(arr[mid]>k){
  47. j=mid-1;
  48. }
  49. else{
  50. i=mid+1;
  51. }
  52. }
  53. return ans;
  54.  
  55. }
  56. }
Success #stdin #stdout 0.11s 55448KB
stdin
Standard input is empty
stdout
4 7