fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static void main (String[] args) throws java.lang.Exception
  11. {
  12. // your code goes here
  13.  
  14. int[] arr={1,2,2,5,5,6,7,8,8,8,8,9,10};
  15. int target=8;
  16. int fo=firstOccurence(arr,target);
  17. int lo=lastOccurence(arr,target);
  18.  
  19. System.out.println("First occurence of " +target+" is on index :"+ fo+ "and last occurence of "+target+" is on index : "+lo);
  20. }
  21.  
  22. private static int firstOccurence(int [] nums,int target){
  23. int fo=-1;
  24.  
  25. int start=0;
  26. int end = nums.length-1;
  27.  
  28. while(start<=end){
  29. int mid=start+(end-start)/2;
  30. if(nums[mid]<target){
  31. start=mid+1;
  32. }
  33. else if(nums[mid]>target){
  34. end=mid-1;
  35. }else{
  36. fo=mid;
  37. end=mid-1;
  38. }
  39. }
  40. return fo;
  41. }
  42.  
  43. private static int lastOccurence(int [] nums,int target){
  44. int lo=-1;
  45.  
  46. int start=0;
  47. int end = nums.length-1;
  48.  
  49. while(start<=end){
  50. int mid=start+(end-start)/2;
  51. if(nums[mid]<target){
  52. start=mid+1;
  53. }
  54. else if(nums[mid]>target){
  55. end=mid-1;
  56. }else{
  57. lo=mid;
  58. start=mid+1;
  59. }
  60. }
  61. return lo;
  62. }
  63. }
Success #stdin #stdout 0.17s 57976KB
stdin
Standard input is empty
stdout
First occurence of 8 is on index :7and last occurence of 8 is on index : 10